前言:最近要实现从FTP服务器下载和上传文件,在网上搜了一下据说 FluentFTP 是个客户端FTP功能的实现,使用还比较顺畅,所以对此展开研究,无奈网上给出的案例并没有想象中的那么简洁,所以想着自己搞一个代码少易读性高的demo来给需要的小伙伴。话不多说直接上案例,文章结尾会有下载地址。
一、首先我们需要通过 NuGet 导入 FluentFTP 包。
二、编写上传和下载部分代码。
using FluentFTP; using System; using System.IO; using System.Net;namespace FluentFTPDemo {class Program{static void Main(string[] args){UploadFile("ftp://192.168.1.200/", "test", "test", "d:\\doctument\\test.pdf");DownloadFile("ftp://192.168.1.200/", "test", "test", "d:\\doctument\\0bc600ee-b36a-4344-b82d-5e23b9de771c.pdf", "/Files/0bc600ee-b36a-4344-b82d-5e23b9de771c");
Console.ReadLine();}/// <summary>/// FTP服务器文件下载到本地/// </summary>/// <param name="ftphost">ftp地址:ftp://192.168.1.200/</param>/// <param name="user">ftp用户名</param>/// <param name="password">ftp密码</param>/// <param name="saveLocalPath">下载到本地的地址:d:\\doctument\\0F5GAHRT4A484TRA5D15FEA.pdf</param>/// <param name="downPath">将要下载的文件在FTP上的路径:/DownFile/0F5GAHRT4A484TRA5D15FEA</param>static void DownloadFile(string ftphost, string user, string password, string saveLocalPath, string downPath){using (FtpClient conn = new FtpClient()){conn.Host = ftphost;conn.Credentials = new NetworkCredential(user, password);byte[] outBuffs;bool flag = conn.Download(out outBuffs, downPath);string s = saveLocalPath.Substring(0, saveLocalPath.LastIndexOf('\\'));Directory.CreateDirectory(s);//如果文件夹不存在就创建它 FileStream fs = new FileStream(saveLocalPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);fs.Write(outBuffs, 0, outBuffs.Length);//清空缓冲区、关闭流 fs.Flush();fs.Close();}} /// <summary>/// 将文件上传到FTP服务器/// </summary>/// <param name="ftphost">ftp地址</param>/// <param name="user">ftp用户名</param>/// <param name="password">ftp密码</param>/// <param name="localPath">本地文件所在的路径:"D:\doctument\test.pdf"</param>static void UploadFile(string ftphost, string user, string password, string localPath){try{using (FtpClient conn = new FtpClient()){conn.Host = ftphost;conn.Credentials = new NetworkCredential(user, password);using (FileStream fs = new FileStream(localPath, FileMode.Open)){string path = localPath.Substring(localPath.LastIndexOf('\\') + 1); //取文件名bool flag = conn.Upload(fs, path);}}}catch (Exception ex){}}} }
链接: https://pan.baidu.com/s/17ACQrZI_90PjMBJ2rRhbwg
提取码: i98j