1.最近项目开发涉及到ftp操作。发现FtpWebRequest类有些操作很麻烦,
例如创建目录只能创建一级目录,多级就失败。删除目录只能删除最后一级的空目录。同样下载也是。
故写下帮助类方便使用。
2.调用方法展示,
var ftp = new FtpHelper("111.111.111.111", "xxxxxxx", "xxxxxx");//初始化ftp,创建ftp对象 ftp.uploadFile("F:\\wms.zip","aaa//bbb");//参数1本地文件,参数2:ftp的目录 ftp.delDirAll("aaa");//参数 要删除的目录的 路径 ftp.downloadAllFile("aaa","F:\\myfile");//参数1:要下载的目录,参数2,保存到本地的目录
3.FtpHelper 代码。后续再补充说明
1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出
2.递归查找所有目录存入list,然后根据 level排序,从最末级开始遍历删除
3.ftp的目录列表比较怪,暂时用截取字符串的获取 目录或文件
////// ftp帮助类 /// public class FtpHelper { private string ftpHostIP { get; set; } private string username { get; set; } private string password { get; set; } private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } } ////// 初始化ftp参数 /// /// ftp主机IP /// ftp账户 /// ftp密码 public FtpHelper(string ftpHostIP, string username, string password) { this.ftpHostIP = ftpHostIP; this.username = username; this.password = password; } ////// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// /// 当前执行的方法 /// ///private bool MethodInvoke(string method, Action action) { if (action != null) { try { action(); //Logger.Write2File($@"FtpHelper.{method}:执行成功"); FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功"); return true; } catch (Exception ex) { FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败", ex.ToString()); // Logger.Write2File(action.GetType().Name, ex.ToString()); return false; } } else { return false; } } /// /// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// /// ////// /// /// private T MethodInvoke (string method, Func func) { if (func != null) { try { FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功"); return func(); //Logger.Write2File($@"FtpHelper.{method}:执行成功"); } catch (Exception ex) { FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败:{ex}"); // Logger.Write2File($@"FtpHelper.{method}:执行失败", ex.ToString()); return default(T); } } else { return default(T); } } private FtpWebRequest GetRequest(string URI) { //根据服务器信息FtpWebRequest创建类的对象 FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI); result.Credentials = new NetworkCredential(username, password); result.KeepAlive = false; result.UsePassive = false; result.UseBinary = true; return result; } /// 上传文件 /// 需要上传的文件 /// 目标路径 public bool uploadFile(string filePath, string dirName = "") { FileInfo fileInfo = new FileInfo(filePath); if (dirName != "") makeDir(dirName); string uri = Path.Combine(ftpURI, dirName, fileInfo.Name); return MethodInvoke($@"uploadFile({filePath},{dirName})", () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.UploadFile; ftp.ContentLength = fileInfo.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; using (FileStream fs = fileInfo.OpenRead()) { using (Stream strm = ftp.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); } fs.Close(); } }); } ////// 检查目录是否存在 /// /// /// ///public bool checkDir(string dirName, string currentDir = "") { string uri = Path.Combine(ftpURI, currentDir); return MethodInvoke($@"checkDir({dirName}{currentDir})", () => { FtpWebRequest ftp = GetRequest(uri); ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { string dir = string.Empty; if (line.IndexOf(" ") > -1) { if (line.Substring(line.IndexOf(" ") + 5).Trim() == dirName) return true; } line = sr.ReadLine(); } sr.Close(); } stream.Close(); return false; }); } /// /// 获取当前目录下的目录及文件 /// /// param name="ftpfileList"> /// ///public List getFtpFile(string dirName) { var ftpfileList = new List (); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($@"getFile({dirName})", () => { var a = new List >(); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("
") > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) }); line = sr.ReadLine(); } sr.Close(); } return ftpfileList; }); } /// /// 获取目录下的所有目录及文件包括其子目录和子文件 /// /// param name="ftpfileList"> /// ///public List getAllFtpFile(List ftpfileList, string dirName, int level = 0) { var flist = new List (); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($@"getFile({dirName})", () => { var a = new List >(); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { flist.Add(new Ftpfile { isDir = line.IndexOf("
") > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) }); ftpfileList.Add(new Ftpfile { isDir = line.IndexOf(" ") > -1, name = line.Substring(39).Trim(), level = level, path = Path.Combine(dirName, line.Substring(39).Trim()) }); line = sr.ReadLine(); } sr.Close(); } var nflist = flist.Where(x => x.isDir).ToList(); if (nflist.Count == 0) return ftpfileList; else return getAllFtpFile(ftpfileList, Path.Combine(dirName, nflist.First().name), level + 1); }); } /// /// 在ftp服务器上创建指定目录,父目录不存在则创建 /// /// 创建的目录名称 public bool makeDir(string dirName) { var dirs = dirName.Split('\\').ToList();//针对多级目录分割 string currentDir = string.Empty; return MethodInvoke($@"makeDir({dirName})", () => { foreach (var dir in dirs) { if (!checkDir(dir, currentDir))//检查目录不存在则创建 { currentDir = Path.Combine(currentDir, dir); string uri = Path.Combine(ftpURI, currentDir); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } else { currentDir = Path.Combine(currentDir, dir); } } }); } /// /// 删除单个文件 /// /// public bool delFile(string filePath) { string uri = Path.Combine(ftpURI, filePath); return MethodInvoke($@"deleteFile({filePath})", () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } ////// 删除最末及空目录 /// /// private bool delDir(string dirName) { string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($@"delDir({dirName})", () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } ///删除目录或者其目录下所有的文件 /// 目录名称 /// 是否删除目录下所有的文件 public void delDirAll(string dirName) { var dlist = getAllFtpFile(new List(),dirName); dlist.OrderByDescending(x => x.level);//降序排列,先删除末及文件或空目录 string uri = Path.Combine(ftpURI, dirName); MethodInvoke($@"delDirAll({dirName})", () => { foreach (var item in dlist) { if (item.isDir)//判断是目录调用目录的删除方法 delDir(item.path); else delFile(item.path); } }); } /// 文件重命名 /// 当前名称 /// 重命名名称 /// 所在的目录 public bool Rename(string currentFilename, string newFilename, string dirName = "") { string uri = Path.Combine(ftpURI, dirName, currentFilename); return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.Rename; ftp.RenameTo = newFilename; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } ////// 下载单个文件 /// /// 从ftp要下载的文件路径 /// 下载至本地路径 /// 文件名 public bool downloadFile(string ftpFilePath, string saveDir, string filename) { string tmpname = Guid.NewGuid().ToString(); string uri = Path.Combine(ftpURI, ftpFilePath); return MethodInvoke($@"downloadFile({ftpFilePath},{saveDir},{filename})", () => { if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.DownloadFile; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew)) { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } responseStream.Close(); } response.Close(); } }); } ////// 从FTP下载整个文件夹 /// /// FTP文件夹路径 /// 保存的本地文件夹路径 public void downloadAllFile(string dirName, string saveDir) { MethodInvoke($@"downloadAllFile({dirName},{saveDir})", () => { Listfiles = getFtpFile(dirName); if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } foreach (var f in files) { if (f.isDir) //文件夹,递归查询 { downloadAllFile(Path.Combine(dirName + f.name), Path.Combine(saveDir + f.name)); } else //文件,直接下载 { downloadFile(Path.Combine(dirName + f.name), saveDir, f.name); } } }); } } public class Ftpfile { public int level { get; set; } = 0; public bool isDir { get; set; } public string name { get; set; } public string path { get; set; } = ""; }
以上所述是小编给大家介绍的C#开发教程之ftp操作方法整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!