# CSharp上传下载简单帮助文件FtpHelper date: 2020-03-19 08:41:13 从网上搜了好几个,感觉这个最简单好用。 NuGet先搜到FluentFTP,加入项目,然后用此Helper。 ```c# using FluentFTP; using System.IO; using System.Net; namespace ChemicalDrugs { class FtpHelper { private string ftphost; private string user; private string password; private string localPath; private string remotePath; public FtpHelper(string loPath, string rePath) { ftphost = "ftp://b"; user = ""; password = ""; localPath = loPath; remotePath = $"/htdocs/{rePath}"; } public bool UploadFile() { 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);//取文件名 conn.Upload(fs, remotePath); } return true; } } catch { return false; } } public bool DownloadFile() { bool flag = false; try { using (FtpClient conn = new FtpClient()) { conn.Host = ftphost; conn.Credentials = new NetworkCredential(user, password); byte[] outBuffs; flag = conn.Download(out outBuffs, remotePath); string s = localPath.Substring(0, localPath.LastIndexOf('\\')); Directory.CreateDirectory(s);//如果文件夹不存在就创建它 FileStream fs = new FileStream(localPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); fs.Write(outBuffs, 0, outBuffs.Length); //清空缓冲区、关闭流 fs.Flush(); fs.Close(); } return flag; } catch { return false; } } } } ```
鲁ICP备17027395号-1