C#开发-ftp操作方法整理
1.整理简化了下C#的ftp操作,方便使用
1.支持创建多级目录
2.批量删除
3.整个目录上传
4.整个目录删除
5.整个目录下载
2.调用方法展示,
- var ftp = new FtpHelper("10.136.12.11", "qdx1213123", "123ddddf");//初始化ftp,创建ftp对象
- ftp.DelAll("test");//删除ftptest目录及其目录下的所有文件
- ftp.UploadAllFile("F:\\test\\wms.zip");//上传单个文件到指定目录
- ftp.UploadAllFile("F:\\test");//将本地test目录的所有文件上传
- ftp.DownloadFile("test\\wms.zip", "F:\\test1");//下载单个目录
- ftp.DownloadAllFile("test", "F:\\test1");//批量下载整个目录
- ftp.MakeDir("aaa\\bbb\\ccc\\ddd");//创建多级目录
3.FtpHelper 代码。
1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出
2.ftp的删除需要递归查找所有目录存入list,然后根据 level倒序排序,从最末级开始遍历删除
3.其他的整个目录操作都是同上
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.IO;
- namespace MyStuday
- {
- /// <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.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
- return true;
- }
- catch (Exception ex)
- {
- FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:\n {ex}");
- // Logger.Write2File(FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");
- 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.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
- //Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
- return func();
- }
- catch (Exception ex)
- {
- //FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:").Line(ex);
- // Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");
- 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="dirName">目标路径</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 = ;
- byte[] buff = new byte[buffLength];
- int contentLen;
- using (FileStream fs = fileInfo.OpenRead())
- {
- using (Stream strm = ftp.GetRequestStream())
- {
- contentLen = fs.Read(buff, , buffLength);
- while (contentLen != )
- {
- strm.Write(buff, , contentLen);
- contentLen = fs.Read(buff, , buffLength);
- }
- strm.Close();
- }
- fs.Close();
- }
- });
- }
- /// <summary>
- /// 从一个目录将其内容复制到另一目录
- /// </summary>
- /// <param name="localDir">源目录</param>
- /// <param name="DirName">目标目录</param>
- public void UploadAllFile(string localDir, string DirName = "")
- {
- string localDirName = string.Empty;
- int targIndex = localDir.LastIndexOf("\\");
- if (targIndex > - && targIndex != (localDir.IndexOf(":\\") + ))
- localDirName = localDir.Substring(, targIndex);
- localDirName = localDir.Substring(targIndex + );
- string newDir = Path.Combine(DirName, localDirName);
- MethodInvoke($@"UploadAllFile({localDir},{DirName})", () =>
- {
- MakeDir(newDir);
- DirectoryInfo directoryInfo = new DirectoryInfo(localDir);
- FileInfo[] files = directoryInfo.GetFiles();
- //复制所有文件
- foreach (FileInfo file in files)
- {
- UploadFile(file.FullName, newDir);
- }
- //最后复制目录
- DirectoryInfo[] directoryInfoArray = directoryInfo.GetDirectories();
- foreach (DirectoryInfo dir in directoryInfoArray)
- {
- UploadAllFile(Path.Combine(localDir, dir.Name), newDir);
- }
- });
- }
- /// <summary>
- /// 删除单个文件
- /// </summary>
- /// <param name="filePath"></param>
- public bool DelFile(string filePath)
- {
- string uri = Path.Combine(ftpURI, filePath);
- return MethodInvoke($@"DelFile({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 bool DelAll(string dirName)
- {
- var list = GetAllFtpFile(new List<ActFile>(),dirName);
- if (list == null) return DelDir(dirName);
- if (list.Count==) return DelDir(dirName);//删除当前目录
- var newlist = list.OrderByDescending(x => x.level);
- foreach (var item in newlist)
- {
- FluentConsole.Yellow.Line($@"level:{item.level},isDir:{item.isDir},path:{item.path}");
- }
- string uri = Path.Combine(ftpURI, dirName);
- return MethodInvoke($@"DelAll({dirName})", () =>
- {
- foreach (var item in newlist)
- {
- if (item.isDir)//判断是目录调用目录的删除方法
- DelDir(item.path);
- else
- DelFile(item.path);
- }
- DelDir(dirName);//删除当前目录
- return true;
- });
- }
- /// <summary>
- /// 下载单个文件
- /// </summary>
- /// <param name="ftpFilePath">从ftp要下载的文件路径</param>
- /// <param name="localDir">下载至本地路径</param>
- /// <param name="filename">文件名</param>
- public bool DownloadFile(string ftpFilePath, string saveDir)
- {
- string filename = ftpFilePath.Substring(ftpFilePath.LastIndexOf("\\") + );
- 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[];
- int read = ;
- do
- {
- read = responseStream.Read(buffer, , buffer.Length);
- fs.Write(buffer, , read);
- } while (!(read == ));
- 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<ActFile> 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);
- }
- }
- });
- }
- /// <summary>
- /// 获取当前目录下的目录及文件
- /// </summary>
- /// param name="ftpfileList"></param>
- /// <param name="dirName"></param>
- /// <returns></returns>
- public List<ActFile> GetFtpFile(string dirName,int ilevel = )
- {
- var ftpfileList = new List<ActFile>();
- string uri = Path.Combine(ftpURI, dirName);
- return MethodInvoke($@"GetFtpFile({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 ActFile { isDir = line.IndexOf("<DIR>") > -, name = line.Substring().Trim(), path = Path.Combine(dirName, line.Substring().Trim()), level= ilevel });
- line = sr.ReadLine();
- }
- sr.Close();
- }
- return ftpfileList;
- });
- }
- /// <summary>
- /// 获取FTP目录下的所有目录及文件包括其子目录和子文件
- /// </summary>
- /// param name="result"></param>
- /// <param name="dirName"></param>
- /// <returns></returns>
- public List<ActFile> GetAllFtpFile(List<ActFile> result,string dirName, int level = )
- {
- var ftpfileList = new List<ActFile>();
- string uri = Path.Combine(ftpURI, dirName);
- return MethodInvoke($@"GetAllFtpFile({dirName})", () =>
- {
- ftpfileList = GetFtpFile(dirName, level);
- result.AddRange(ftpfileList);
- var newlist = ftpfileList.Where(x => x.isDir).ToList();
- foreach (var item in newlist)
- {
- GetAllFtpFile(result,item.path, level+);
- }
- return result;
- });
- }
- /// <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))
- {
- if (line.IndexOf("<DIR>") > -)
- {
- if (line.Substring().Trim() == dirName)
- return true;
- }
- line = sr.ReadLine();
- }
- sr.Close();
- }
- stream.Close();
- return false;
- });
- }
- /// </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="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();
- });
- }
- }
- public class ActFile
- {
- public int level { get; set; } = ;
- public bool isDir { get; set; }
- public string name { get; set; }
- public string path { get; set; } = "";
- }
- }
C#开发-ftp操作方法整理的更多相关文章
- ftp操作方法整理
1.整理简化了下C#的ftp操作,方便使用 1.支持创建多级目录 2.批量删除 3.整个目录上传 4.整个目录删除 5.整个目录下载 2.调用方法展示, var ftp ...
- C#开发--FTP操作方法管理
1.整理简化了下C#的ftp操作,方便使用 1.支持创建多级目录 2.批量删除 3.整个目录上传 4.整个目录删除 5.整个目录下载 2.调用方法展示, var ftp ...
- .NET Web开发技术简单整理 转
.NET Web开发技术简单整理 原文:http://www.cnblogs.com/SanMaoSpace/p/3157293.html 在最初学习一些编程语言.一些编程技术的时候,做的更多的是如何 ...
- 我自己总结的C#开发命名规范整理了一份
我自己总结的C#开发命名规范整理了一份 标签: 开发规范文档标准语言 2014-06-27 22:58 3165人阅读 评论(1) 收藏 举报 分类: C#(39) 版权声明:本文为博主原创文章, ...
- Android开发——Fragment知识整理(二)
0. 前言 Android开发中的Fragment的应用非常广泛,在Android开发--Fragment知识整理(一)中简单介绍了关于Fragment的生命周期,常用API,回退栈的应用等知识.这 ...
- Android开发——Fragment知识整理(一)
0. 前言 Fragment,顾名思义是片段的意思,可以把Fragment当成Activity的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成.Fragment需要被嵌 ...
- .NET Web开发技术简单整理
在最初学习一些编程语言.一些编程技术的时候,做的更多的是如何使用该技术,如何更好的使用该技术解决问题,而没有去关注它的相关性.关注它的理论支持,这种学习技术的方式是短平快.其实工作中有时候也是这样,公 ...
- 转载:.NET Web开发技术简单整理
在最初学习一些编程语言.一些编程技术的时候,做的更多的是如何使用该技术,如何更好的使用该技术解决问题,而没有去关注它的相关性.关注它的理论支持,这种学习技术的方式是短平快.其实工作中有时候也是这样,公 ...
- 移动端 Web 开发前端知识整理
文章来源: http://www.restran.net/2015/05/14/mobile-web-front-end-collections/ 最近整理的移动端 Web 开发前端知识,不定期更新. ...
随机推荐
- (八)学习MVC之三级联动
1.新建项目,MVC选择基本模板 2.新建类:Model/Student.cs,数据库信息有三个实体:分别是年级.班级和学生. using System; using System.Collectio ...
- javascript六难题
1.下面代码的运行效果是什么?为什么? <html> <head> <meta charset="utf-8"> <title>DO ...
- A Fast Priority Queue Implementation of the Dijkstra Shortest Path Algorithm
http://www.codeproject.com/Articles/24816/A-Fast-Priority-Queue-Implementation-of-the-Dijkst http:// ...
- C# 创建WebServices及调用方法
发布WebServices 1.创建 ASP.NET Web 服务应用程序 SayHelloWebServices 这里需要说明一下,由于.NET Framework4.0取消了WebService ...
- as3 工具类分享 CookieMgr
今天分享一个工具类 CookieMgr,功能就是读取和写入 SharedObject 对象.很简单,都是静态方法,就不多说了 package org.polarbear.core { import f ...
- Jquery UI的datepicker插件使用方法
原文链接;http://www.ido321.com/375.html Jquery UI是一个非常丰富的Jquery插件,并且UI的各部分插件可以独自分离出来使用,这是其他很多Jquery插件没有的 ...
- python 中 struct 用法
下面就介绍这个模块中的几个方法. struct.pack():我的理解是,python利用 struct模块将字符(比如说 int,long ,unsized int 等)拆成 字节流(用十六进制表示 ...
- 【OpenGL】入门
根据OpenGL蓝宝书(OpenGL超级宝典)来入门,写的比较细,易懂,这里给我贴代码和记录零碎的事儿用 第一个代码 #include <gl/glut.h> void RenderSce ...
- algorithm@ O(3/2 n) time to findmaximum and minimum in a array
public static int[] max_min(int[] a){ //res[0] records the minimum value while res[1] records the ma ...
- 【noip2011】观光公交
题解: 做这题的时候为了敢速度- - 直接orz了神小黑的题解 其实我还是有想一个拙计的方法的- - dp:f[i][j] 表示到i点使用j个加速器 在i前上车的人的时间和 轻松愉悦转移之 - - 但 ...