查看: 2076|回复: 0

[ASP.NET教程] C#实现FTP客户端的案例

发表于 2018-2-10 08:00:07

本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用。

思路:

通过读取FTP站点的目录信息,列出对应的文件及文件夹。
双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作。
通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作。

涉及知识点:

FtpWebRequest【实现文件传输协议 (FTP) 客户端】 / FtpWebResponse【封装文件传输协议 (FTP) 服务器对请求的响应】Ftp的操作主要集中在两个类中。
FlowLayoutPanel 【流布局面板】表示一个沿水平或垂直方向动态排放其内容的面板。
ContextMenuStrip 【快捷菜单】 主要用于右键菜单。
资源文件:Resources 用于存放图片及其他资源。

效果图如下

左边:双击文件夹进入子目录,点击工具栏按钮‘上级目录'返回。文件点击右键进行操作。

右边:文件夹则点击前面+号展开。文件则点击右键进行上传。

核心代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace FtpClient
  10. {
  11. public class FtpHelper
  12. {
  13. #region 属性与构造函数
  14. /// <summary>
  15. /// IP地址
  16. /// </summary>
  17. public string IpAddr { get; set; }
  18. /// <summary>
  19. /// 相对路径
  20. /// </summary>
  21. public string RelatePath { get; set; }
  22. /// <summary>
  23. /// 端口号
  24. /// </summary>
  25. public string Port { get; set; }
  26. /// <summary>
  27. /// 用户名
  28. /// </summary>
  29. public string UserName { get; set; }
  30. /// <summary>
  31. /// 密码
  32. /// </summary>
  33. public string Password { get; set; }
  34. public FtpHelper() {
  35. }
  36. public FtpHelper(string ipAddr, string port, string userName, string password) {
  37. this.IpAddr = ipAddr;
  38. this.Port = port;
  39. this.UserName = userName;
  40. this.Password = password;
  41. }
  42. #endregion
  43. #region 方法
  44. /// <summary>
  45. /// 下载文件
  46. /// </summary>
  47. /// <param name="filePath"></param>
  48. /// <param name="isOk"></param>
  49. public void DownLoad(string filePath, out bool isOk) {
  50. string method = WebRequestMethods.Ftp.DownloadFile;
  51. var statusCode = FtpStatusCode.DataAlreadyOpen;
  52. FtpWebResponse response = callFtp(method);
  53. ReadByBytes(filePath, response, statusCode, out isOk);
  54. }
  55. public void UpLoad(string file,out bool isOk)
  56. {
  57. isOk = false;
  58. FileInfo fi = new FileInfo(file);
  59. FileStream fs = fi.OpenRead();
  60. long length = fs.Length;
  61. string uri = string.Format("ftp://{0}:小贝{2}", this.IpAddr, this.Port, this.RelatePath);
  62. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
  63. request.Credentials = new NetworkCredential(UserName, Password);
  64. request.Method = WebRequestMethods.Ftp.UploadFile;
  65. request.UseBinary = true;
  66. request.ContentLength = length;
  67. request.Timeout = 10 * 1000;
  68. try
  69. {
  70. Stream stream = request.GetRequestStream();
  71. int BufferLength = 2048; //2K
  72. byte[] b = new byte[BufferLength];
  73. int i;
  74. while ((i = fs.Read(b, 0, BufferLength)) > 0)
  75. {
  76. stream.Write(b, 0, i);
  77. }
  78. stream.Close();
  79. stream.Dispose();
  80. isOk = true;
  81. }
  82. catch (Exception ex)
  83. {
  84. Console.WriteLine(ex.ToString());
  85. }
  86. finally {
  87. if (request != null)
  88. {
  89. request.Abort();
  90. request = null;
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// 删除文件
  96. /// </summary>
  97. /// <param name="isOk"></param>
  98. /// <returns></returns>
  99. public string[] DeleteFile(out bool isOk) {
  100. string method = WebRequestMethods.Ftp.DeleteFile;
  101. var statusCode = FtpStatusCode.FileActionOK;
  102. FtpWebResponse response = callFtp(method);
  103. return ReadByLine(response, statusCode, out isOk);
  104. }
  105. /// <summary>
  106. /// 展示目录
  107. /// </summary>
  108. public string[] ListDirectory(out bool isOk)
  109. {
  110. string method = WebRequestMethods.Ftp.ListDirectoryDetails;
  111. var statusCode = FtpStatusCode.DataAlreadyOpen;
  112. FtpWebResponse response= callFtp(method);
  113. return ReadByLine(response, statusCode, out isOk);
  114. }
  115. /// <summary>
  116. /// 设置上级目录
  117. /// </summary>
  118. public void SetPrePath()
  119. {
  120. string relatePath = this.RelatePath;
  121. if (string.IsNullOrEmpty(relatePath) || relatePath.LastIndexOf("/") == 0 )
  122. {
  123. relatePath = "";
  124. }
  125. else {
  126. relatePath = relatePath.Substring(0, relatePath.LastIndexOf("/"));
  127. }
  128. this.RelatePath = relatePath;
  129. }
  130. #endregion
  131. #region 私有方法
  132. /// <summary>
  133. /// 调用Ftp,将命令发往Ftp并返回信息
  134. /// </summary>
  135. /// <param name="method">要发往Ftp的命令</param>
  136. /// <returns></returns>
  137. private FtpWebResponse callFtp(string method)
  138. {
  139. string uri = string.Format("ftp://{0}:小贝{2}", this.IpAddr, this.Port, this.RelatePath);
  140. FtpWebRequest request; request = (FtpWebRequest)FtpWebRequest.Create(uri);
  141. request.UseBinary = true;
  142. request.UsePassive = true;
  143. request.Credentials = new NetworkCredential(UserName, Password);
  144. request.KeepAlive = false;
  145. request.Method = method;
  146. FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  147. return response;
  148. }
  149. /// <summary>
  150. /// 按行读取
  151. /// </summary>
  152. /// <param name="response"></param>
  153. /// <param name="statusCode"></param>
  154. /// <param name="isOk"></param>
  155. /// <returns></returns>
  156. private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode,out bool isOk) {
  157. List<string> lstAccpet = new List<string>();
  158. int i = 0;
  159. while (true)
  160. {
  161. if (response.StatusCode == statusCode)
  162. {
  163. using (StreamReader sr = new StreamReader(response.GetResponseStream()))
  164. {
  165. string line = sr.ReadLine();
  166. while (!string.IsNullOrEmpty(line))
  167. {
  168. lstAccpet.Add(line);
  169. line = sr.ReadLine();
  170. }
  171. }
  172. isOk = true;
  173. break;
  174. }
  175. i++;
  176. if (i > 10)
  177. {
  178. isOk = false;
  179. break;
  180. }
  181. Thread.Sleep(200);
  182. }
  183. response.Close();
  184. return lstAccpet.ToArray();
  185. }
  186. private void ReadByBytes(string filePath,FtpWebResponse response, FtpStatusCode statusCode, out bool isOk)
  187. {
  188. isOk = false;
  189. int i = 0;
  190. while (true)
  191. {
  192. if (response.StatusCode == statusCode)
  193. {
  194. long length = response.ContentLength;
  195. int bufferSize = 2048;
  196. int readCount;
  197. byte[] buffer = new byte[bufferSize];
  198. using (FileStream outputStream = new FileStream(filePath, FileMode.Create))
  199. {
  200. using (Stream ftpStream = response.GetResponseStream())
  201. {
  202. readCount = ftpStream.Read(buffer, 0, bufferSize);
  203. while (readCount > 0)
  204. {
  205. outputStream.Write(buffer, 0, readCount);
  206. readCount = ftpStream.Read(buffer, 0, bufferSize);
  207. }
  208. }
  209. }
  210. break;
  211. }
  212. i++;
  213. if (i > 10)
  214. {
  215. isOk = false;
  216. break;
  217. }
  218. Thread.Sleep(200);
  219. }
  220. response.Close();
  221. }
  222. #endregion
  223. }
  224. /// <summary>
  225. /// Ftp内容类型枚举
  226. /// </summary>
  227. public enum FtpContentType
  228. {
  229. undefined = 0,
  230. file = 1,
  231. folder = 2
  232. }
  233. }
复制代码

源码链接如下:案例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

您可能感兴趣的文章:

  • C#版ftp方法实现类的代码
  • C# FTP,GetResponse(),远程服务器返回错误
  • 关于c#连接ftp进行上传下载实现原理及代码
  • C# winfrom 模拟ftp文件管理实现代码
  • c#操作ftp类分享
  • C#操作FTP出现500错误解决办法
  • C#实现自定义FTP操作封装类实例
  • 分享用于操作FTP的客户端C#类
  • C#操作ftp类完整实例
  • FtpHelper实现ftp服务器文件读写操作(C#)


回复

使用道具 举报