c#一个FTP操作封装类FTPHelper

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. public class FTPHelper
  8. {
  9. /// <summary>
  10. /// FTP请求对象
  11. /// </summary>
  12. FtpWebRequest request = null;
  13. /// <summary>
  14. /// FTP响应对象
  15. /// </summary>
  16. FtpWebResponse response = null;
  17. /// <summary>
  18. /// FTP服务器地址
  19. /// </summary>
  20. public string ftpURI { get; private set; }
  21. /// <summary>
  22. /// FTP服务器IP
  23. /// </summary>
  24. public string ftpServerIP { get; private set; }
  25. /// <summary>
  26. /// FTP服务器默认目录
  27. /// </summary>
  28. public string ftpRemotePath { get; private set; }
  29. /// <summary>
  30. /// FTP服务器登录用户名
  31. /// </summary>
  32. public string ftpUserID { get; private set; }
  33. /// <summary>
  34. /// FTP服务器登录密码
  35. /// </summary>
  36. public string ftpPassword { get; private set; }
  37. /// <summary>
  38. /// 初始化
  39. /// </summary>
  40. /// <param name="FtpServerIP">FTP连接地址</param>
  41. /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
  42. /// <param name="FtpUserID">用户名</param>
  43. /// <param name="FtpPassword">密码</param>
  44. public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, string ftpPassword)
  45. {
  46. this.ftpServerIP = ftpServerIP;
  47. this.ftpRemotePath = ftpRemotePath;
  48. this.ftpUserID = ftpUserID;
  49. this.ftpPassword = ftpPassword;
  50. this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  51. }
  52. ~FTPHelper()
  53. {
  54. if (response != null)
  55. {
  56. response.Close();
  57. response = null;
  58. }
  59. if (request != null)
  60. {
  61. request.Abort();
  62. request = null;
  63. }
  64. }
  65. /// <summary>
  66. /// 建立FTP链接,返回响应对象
  67. /// </summary>
  68. /// <param name="uri">FTP地址</param>
  69. /// <param name="ftpMethod">操作命令</param>
  70. /// <returns></returns>
  71. private FtpWebResponse Open(Uri uri, string ftpMethod)
  72. {
  73. request = (FtpWebRequest)FtpWebRequest.Create(uri);
  74. request.Method = ftpMethod;
  75. request.UseBinary = true;
  76. request.KeepAlive = false;
  77. request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
  78. return (FtpWebResponse)request.GetResponse();
  79. }
  80. /// <summary>
  81. /// 建立FTP链接,返回请求对象
  82. /// </summary>
  83. /// <param name="uri">FTP地址</param>
  84. /// <param name="ftpMethod">操作命令</param>
  85. private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)
  86. {
  87. request = (FtpWebRequest)WebRequest.Create(uri);
  88. request.Method = ftpMethod;
  89. request.UseBinary = true;
  90. request.KeepAlive = false;
  91. request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
  92. return request;
  93. }
  94. /// <summary>
  95. /// 创建目录
  96. /// </summary>
  97. /// <param name="remoteDirectoryName">目录名</param>
  98. public void CreateDirectory(string remoteDirectoryName)
  99. {
  100. response = Open(new Uri(ftpURI + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory);
  101. }
  102. /// <summary>
  103. /// 更改目录或文件名
  104. /// </summary>
  105. /// <param name="currentName">当前名称</param>
  106. /// <param name="newName">修改后新名称</param>
  107. public void ReName(string currentName, string newName)
  108. {
  109. request = OpenRequest(new Uri(ftpURI + currentName), WebRequestMethods.Ftp.Rename);
  110. request.RenameTo = newName;
  111. response = (FtpWebResponse)request.GetResponse();
  112. }
  113. /// <summary>
  114. /// 切换当前目录
  115. /// </summary>
  116. /// <param name="IsRoot">true:绝对路径 false:相对路径</param>
  117. public void GotoDirectory(string DirectoryName, bool IsRoot)
  118. {
  119. if (IsRoot)
  120. ftpRemotePath = DirectoryName;
  121. else
  122. ftpRemotePath += "/" + DirectoryName;
  123. ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  124. }
  125. /// <summary>
  126. /// 删除目录(包括下面所有子目录和子文件)
  127. /// </summary>
  128. /// <param name="remoteDirectoryName">要删除的带路径目录名:如web/test</param>
  129. /*
  130. * 例:删除test目录
  131. FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password");
  132. helper.RemoveDirectory("web/test");
  133. */
  134. public void RemoveDirectory(string remoteDirectoryName)
  135. {
  136. GotoDirectory(remoteDirectoryName, true);
  137. var listAll = ListFilesAndDirectories();
  138. foreach (var m in listAll)
  139. {
  140. if (m.IsDirectory)
  141. RemoveDirectory(m.Path);
  142. else
  143. DeleteFile(m.Name);
  144. }
  145. GotoDirectory(remoteDirectoryName, true);
  146. response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
  147. }
  148. /// <summary>
  149. /// 文件上传
  150. /// </summary>
  151. /// <param name="localFilePath">本地文件路径</param>
  152. public void Upload(string localFilePath)
  153. {
  154. FileInfo fileInf = new FileInfo(localFilePath);
  155. request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile);
  156. request.ContentLength = fileInf.Length;
  157. int buffLength = 2048;
  158. byte[] buff = new byte[buffLength];
  159. int contentLen;
  160. using (var fs = fileInf.OpenRead())
  161. {
  162. using (var strm = request.GetRequestStream())
  163. {
  164. contentLen = fs.Read(buff, 0, buffLength);
  165. while (contentLen != 0)
  166. {
  167. strm.Write(buff, 0, contentLen);
  168. contentLen = fs.Read(buff, 0, buffLength);
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// 删除文件
  175. /// </summary>
  176. /// <param name="remoteFileName">要删除的文件名</param>
  177. public void DeleteFile(string remoteFileName)
  178. {
  179. response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile);
  180. }
  181. /// <summary>
  182. /// 获取当前目录的文件和一级子目录信息
  183. /// </summary>
  184. /// <returns></returns>
  185. public List<FileStruct> ListFilesAndDirectories()
  186. {
  187. var fileList = new List<FileStruct>();
  188. response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);
  189. using (var stream = response.GetResponseStream())
  190. {
  191. using (var sr = new StreamReader(stream))
  192. {
  193. string line = null;
  194. while ((line = sr.ReadLine()) != null)
  195. {
  196. //line的格式如下:
  197. //08-18-13  11:05PM       <DIR>          aspnet_client
  198. //09-22-13  11:39PM                 2946 Default.aspx
  199. DateTime dtDate = DateTime.ParseExact(line.Substring(0, 8), "MM-dd-yy", null);
  200. DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(8, 9));
  201. string[] arrs = line.Split(‘ ‘);
  202. var model = new FileStruct()
  203. {
  204. IsDirectory = line.IndexOf("<DIR>") > 0 ? true : false,
  205. CreateTime = dtDateTime,
  206. Name = arrs[arrs.Length - 1],
  207. Path = ftpRemotePath + "/" + arrs[arrs.Length - 1]
  208. };
  209. fileList.Add(model);
  210. }
  211. }
  212. }
  213. return fileList;
  214. }
  215. /// <summary>
  216. /// 列出当前目录的所有文件
  217. /// </summary>
  218. public List<FileStruct> ListFiles()
  219. {
  220. var listAll = ListFilesAndDirectories();
  221. var listFile = listAll.Where(m => m.IsDirectory == false).ToList();
  222. return listFile;
  223. }
  224. /// <summary>
  225. /// 列出当前目录的所有一级子目录
  226. /// </summary>
  227. public List<FileStruct> ListDirectories()
  228. {
  229. var listAll = ListFilesAndDirectories();
  230. var listFile = listAll.Where(m => m.IsDirectory == true).ToList();
  231. return listFile;
  232. }
  233. /// <summary>
  234. /// 判断当前目录下指定的子目录或文件是否存在
  235. /// </summary>
  236. /// <param name="remoteName">指定的目录或文件名</param>
  237. public bool IsExist(string remoteName)
  238. {
  239. var list = ListFilesAndDirectories();
  240. if (list.Count(m => m.Name == remoteName) > 0)
  241. return true;
  242. return false;
  243. }
  244. /// <summary>
  245. /// 判断当前目录下指定的一级子目录是否存在
  246. /// </summary>
  247. /// <param name="RemoteDirectoryName">指定的目录名</param>
  248. public bool IsDirectoryExist(string remoteDirectoryName)
  249. {
  250. var listDir = ListDirectories();
  251. if (listDir.Count(m => m.Name == remoteDirectoryName) > 0)
  252. return true;
  253. return false;
  254. }
  255. /// <summary>
  256. /// 判断当前目录下指定的子文件是否存在
  257. /// </summary>
  258. /// <param name="RemoteFileName">远程文件名</param>
  259. public bool IsFileExist(string remoteFileName)
  260. {
  261. var listFile = ListFiles();
  262. if (listFile.Count(m => m.Name == remoteFileName) > 0)
  263. return true;
  264. return false;
  265. }
  266. /// <summary>
  267. /// 下载
  268. /// </summary>
  269. /// <param name="saveFilePath">下载后的保存路径</param>
  270. /// <param name="downloadFileName">要下载的文件名</param>
  271. public void Download(string saveFilePath, string downloadFileName)
  272. {
  273. using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create))
  274. {
  275. response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
  276. using (Stream ftpStream = response.GetResponseStream())
  277. {
  278. long cl = response.ContentLength;
  279. int bufferSize = 2048;
  280. int readCount;
  281. byte[] buffer = new byte[bufferSize];
  282. readCount = ftpStream.Read(buffer, 0, bufferSize);
  283. while (readCount > 0)
  284. {
  285. outputStream.Write(buffer, 0, readCount);
  286. readCount = ftpStream.Read(buffer, 0, bufferSize);
  287. }
  288. }
  289. }
  290. }
  291. }
  292. public class FileStruct
  293. {
  294. /// <summary>
  295. /// 是否为目录
  296. /// </summary>
  297. public bool IsDirectory { get; set; }
  298. /// <summary>
  299. /// 创建时间
  300. /// </summary>
  301. public DateTime CreateTime { get; set; }
  302. /// <summary>
  303. /// 文件或目录名称
  304. /// </summary>
  305. public string Name { get; set; }
  306. /// <summary>
  307. /// 路径
  308. /// </summary>
  309. public string Path { get; set; }
  310. }
时间: 2024-08-30 02:20:06

c#一个FTP操作封装类FTPHelper的相关文章

【C#】工具类-FTP操作封装类FTPHelper

转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; public class FTPHelper { /// <summary> /// FTP请求对象 /// </summary> F

C#实现自定义FTP操作封装类实例

本文实例讲述了C#实现自定义FTP操作封装类.分享给大家供大家参考.具体如下: 这个C#类封装了FTP的常用操作,包括连接ftp服务器.列表服务器上的目录和文件,从ftp下载文件,上传文件到ftp服务器等等 using System; using System.Text; using System.IO; namespace DotNet.Utilities { public class FTPOperater { #region 属性 private FTPClient ftp; /// <s

[转]C# FTP操作类

转自 http://www.cnblogs.com/Liyuting/p/7084718.html using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ManagementProject { public class FTPHel

[Java] 使用 Apache的 Commons-net库 实现FTP操作

因为最近工作中需要用到FTP操作,而手上又没有现成的FTP代码.就去网上找了一下,发现大家都使用Apache的 Commons-net库中的FTPClient. 但是,感觉用起来不太方便.又在网上找到了很多封装过的.觉得也不是很好用.于是就自己写了一个.网上大多是例子都是直接对文件进行操作,而我更需要的是读到内存,或者从内存上写.并且有很多实用单例模式,但是我觉得如果调用比较多的话,可能会出现问题. 1 /** 2 * 封装了一些FTP操作 3 */ 4 import java.io.Buffe

FTP操作类

using System; using System.Collections.Generic; using System.Net; using System.IO; namespace HGFTP { /// <summary> /// FTP客户端操作类 /// </summary> public class FTPTools { #region 构造函数 /// <summary> /// 创建FTP工具 /// <para> /// 默认不使用SSL,

利于Wininet创建一个FTP客户端的步骤

Wininet是Win32关于网络的API,MFC也有对于Wininet的封装,可以利用这组API实现FTP和HTTP通信. Wininet API的头文件:Wininet.下面是Wininet建立FTP客户端的一般步骤.第一步:初始话Wininet,实际上就是设置一些关于是否使用代理,访问方式等的参数.第二步:建立一个FTP链接.第三步:操作ftp服务器上的文件.第四步:关闭各种句柄. 作用 函数原型 说明 初始Wininet函数 HINTERNET InternetOpen( LPCTSTR

用 Python实现一个ftp+CRT

转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5590004.html  本来最初的想法是实现一个ftp服务器,用来实现用户的登陆注册和文件的断点上传下载等,结果做着做着就连CRT也顺带着跟着完成了,然后就变成了这样一个'不伦不类'的工具.用到的知识有hashlib加密密码传输,面向对象,sockeserver支持多客户访问,os.subprocess来处理系统自带的命令,然后自定义上传下载命令,以及如何实现断点续传,传输过程中的粘包问题,以及如何反射处理用户的

Java的ftp操作

下面是FtpClient类的一些介绍: sun.net.ftp.FtpClient.,该类库首要供给了用于树立FTP衔接的类.运用这些类的办法,编程人员能够长途登录到FTP服务器,罗列该服务器上的目录,设置传输协议,以及传送文件.FtpClient类涵盖了简直一切FTP的功用,FtpClient的实例变量保留了有关树立"署理"的各种信息.下面给出了这些实例变量: public static boolean useFtpProxy 这个变量用于标明FTP传输过程中是不是运用了一个署理,因

Linux中如何搭建一个ftp服务服务器-超详细

ftp工作是会启动两个通道: 控制通道 , 数据通道 在ftp协议中,控制连接均是由客户端发起的,而数据连接有两种模式:port模式(主动模式)和pasv(被动模式) PORT模式: 在客户端需要接收数据时,ftp_client(大于1024的随机端口)-PORT命令->ftp_server(21)  发送PORT命令,这个PORT命令包含了客户端是用什么端口来接收数据(大于1024的随机端口),在传送数据时,ftp_server将通过自己的TCP 20 端口和PORT中包含的端口建立新的连接来