C#开发教程之ftp操作方法整理
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的目录列表比较怪,暂时用截取字符串的获取 目录或文件
/// <summary> /// ftp帮助类 /// </summary> 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}/"; } } /// <summary> /// 初始化ftp参数 /// </summary> /// <param name="ftpHostIP">ftp主机IP</param> /// <param name="username">ftp账户</param> /// <param name="password">ftp密码</param> public FtpHelper(string ftpHostIP, string username, string password) { this.ftpHostIP = ftpHostIP; this.username = username; this.password = password; } /// <summary> /// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// </summary> /// <param name="method">当前执行的方法</param> /// <param name="action"></param> /// <returns></returns> 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; } } /// <summary> /// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// </summary> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="method"></param> /// <param name="func"></param> /// <returns></returns> private T MethodInvoke<T>(string method, Func<T> 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; } /// <summary> 上传文件</summary> /// <param name="filePath">需要上传的文件</param> /// <param name="targetDir">目标路径</param> 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(); } }); } /// <summary> /// 检查目录是否存在 /// </summary> /// <param name="dirName"></param> /// <param name="currentDir"></param> /// <returns></returns> 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("<DIR>") > -1) { if (line.Substring(line.IndexOf("<DIR>") + 5).Trim() == dirName) return true; } line = sr.ReadLine(); } sr.Close(); } stream.Close(); return false; }); } /// <summary> /// 获取当前目录下的目录及文件 /// </summary> /// param name="ftpfileList"></param> /// <param name="dirName"></param> /// <returns></returns> public List<Ftpfile> getFtpFile(string dirName) { var ftpfileList = new List<Ftpfile>(); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($@"getFile({dirName})", () => { var a = new List<List<string>>(); 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("<DIR>") > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) }); line = sr.ReadLine(); } sr.Close(); } return ftpfileList; }); } /// <summary> /// 获取目录下的所有目录及文件包括其子目录和子文件 /// </summary> /// param name="ftpfileList"></param> /// <param name="dirName"></param> /// <returns></returns> public List<Ftpfile> getAllFtpFile(List<Ftpfile> ftpfileList, string dirName, int level = 0) { var flist = new List<Ftpfile>(); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($@"getFile({dirName})", () => { var a = new List<List<string>>(); 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("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) }); ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -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); }); } /// </summary> /// 在ftp服务器上创建指定目录,父目录不存在则创建 /// </summary> /// <param name="dirName">创建的目录名称</param> 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); } } }); } /// <summary> /// 删除单个文件 /// </summary> /// <param name="filePath"></param> 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(); }); } /// <summary> /// 删除最末及空目录 /// </summary> /// <param name="dirName"></param> 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(); }); } /// <summary> 删除目录或者其目录下所有的文件 </summary> /// <param name="dirName">目录名称</param> /// <param name="ifDelSub">是否删除目录下所有的文件</param> public void delDirAll(string dirName) { var dlist = getAllFtpFile(new List<Ftpfile>(),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); } }); } /// <summary>文件重命名 </summary> /// <param name="currentFilename">当前名称</param> /// <param name="newFilename">重命名名称</param> /// <param name="currentFilename">所在的目录</param> 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(); }); } /// <summary> /// 下载单个文件 /// </summary> /// <param name="ftpFilePath">从ftp要下载的文件路径</param> /// <param name="localDir">下载至本地路径</param> /// <param name="filename">文件名</param> 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(); } }); } /// <summary> /// 从FTP下载整个文件夹 /// </summary> /// <param name="dirName">FTP文件夹路径</param> /// <param name="saveDir">保存的本地文件夹路径</param> public void downloadAllFile(string dirName, string saveDir) { MethodInvoke($@"downloadAllFile({dirName},{saveDir})", () => { List<Ftpfile> files = 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操作方法整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
上一篇:BootStrap mvcpager分页样式(get请求,刷新页面)
栏 目:C#教程
下一篇:快速解决owin返回json字符串多带了双引号"多了重string转义字符串
本文标题:C#开发教程之ftp操作方法整理
本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6329.html
您可能感兴趣的文章
- 01-10C#一个简单的定时小程序实现代码
- 01-10微信开放平台之网站授权微信登录功能
- 01-10C#调用WebService实例开发
- 01-10C#编程自学之数据类型和变量二
- 01-10C#编程自学之开篇介绍
- 01-10C#编程自学之数据类型和变量三
- 01-10C#编程自学之运算符和表达式
- 01-10实现ASP.NET无刷新下载并提示下载完成的开发思路
- 01-10C#编程自学之类和对象
- 01-10C#编程自学之数据类型和变量一
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-11ajax实现页面的局部加载
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 01-10SublimeText编译C开发环境设置
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法实例总结
- 04-02jquery与jsp,用jquery