FtpHelper.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. using System.Threading;
  8. namespace SiwiFms.Helper
  9. {
  10. public class FtpHelper
  11. {
  12. // 默认常量定义
  13. public static string rootPath = "/";
  14. private static readonly int defaultReadWriteTimeout = 300000;
  15. private static readonly int defaultFtpPort = 21;
  16. #region 设置初始化参数
  17. private string host = string.Empty;
  18. public string Host
  19. {
  20. get
  21. {
  22. return this.host ?? string.Empty;
  23. }
  24. }
  25. private string username = string.Empty;
  26. public string Username
  27. {
  28. get
  29. {
  30. return this.username;
  31. }
  32. }
  33. private string password = string.Empty;
  34. public string Password
  35. {
  36. get
  37. {
  38. return this.password;
  39. }
  40. }
  41. IWebProxy proxy = null;
  42. public IWebProxy Proxy
  43. {
  44. get
  45. {
  46. return this.proxy;
  47. }
  48. set
  49. {
  50. this.proxy = value;
  51. }
  52. }
  53. private int port = defaultFtpPort;
  54. public int Port
  55. {
  56. get
  57. {
  58. return port;
  59. }
  60. set
  61. {
  62. this.port = value;
  63. }
  64. }
  65. private bool enableSsl = false;
  66. public bool EnableSsl
  67. {
  68. get
  69. {
  70. return enableSsl;
  71. }
  72. }
  73. private bool usePassive = true;
  74. public bool UsePassive
  75. {
  76. get
  77. {
  78. return usePassive;
  79. }
  80. set
  81. {
  82. this.usePassive = value;
  83. }
  84. }
  85. private bool useBinary = true;
  86. public bool UserBinary
  87. {
  88. get
  89. {
  90. return useBinary;
  91. }
  92. set
  93. {
  94. this.useBinary = value;
  95. }
  96. }
  97. private string remotePath = rootPath;
  98. public string RemotePath
  99. {
  100. get
  101. {
  102. return remotePath;
  103. }
  104. set
  105. {
  106. string result = rootPath;
  107. if (!string.IsNullOrEmpty(value) && value != rootPath)
  108. {
  109. result = Path.Combine(rootPath, value.TrimStart('/').TrimEnd('/'))+"/"; // 进行路径的拼接
  110. }
  111. this.remotePath = result;
  112. }
  113. }
  114. private int readWriteTimeout = defaultReadWriteTimeout;
  115. public int ReadWriteTimeout
  116. {
  117. get
  118. {
  119. return readWriteTimeout;
  120. }
  121. set
  122. {
  123. this.readWriteTimeout = value;
  124. }
  125. }
  126. #endregion
  127. #region 构造函数
  128. public FtpHelper(string host, string username, string password)
  129. : this(host, username, password, defaultFtpPort, null, false, true, true, defaultReadWriteTimeout)
  130. {
  131. }
  132. public FtpHelper(string host, string username, string password,int port)
  133. : this(host, username, password, port, null, false, true, true, defaultReadWriteTimeout)
  134. {
  135. }
  136. /// <summary>
  137. /// 构造函数
  138. /// </summary>
  139. /// <param name="host">主机名</param>
  140. /// <param name="username">用户名</param>
  141. /// <param name="password">密码</param>
  142. /// <param name="port">端口号 默认21</param>
  143. /// <param name="proxy">代理 默认没有</param>
  144. /// <param name="enableSsl">是否使用ssl 默认不用</param>
  145. /// <param name="useBinary">使用二进制</param>
  146. /// <param name="usePassive">获取或设置客户端应用程序的数据传输过程的行为</param>
  147. /// <param name="readWriteTimeout">读写超时时间 默认5min</param>
  148. public FtpHelper(string host, string username, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive, int readWriteTimeout)
  149. {
  150. this.host = host.ToLower().StartsWith("ftp://") ? host : "ftp://" + host;
  151. this.username = username;
  152. this.password = password;
  153. this.port = port;
  154. this.proxy = proxy;
  155. this.enableSsl = enableSsl;
  156. this.useBinary = useBinary;
  157. this.usePassive = usePassive;
  158. this.readWriteTimeout = readWriteTimeout;
  159. }
  160. #endregion
  161. /// <summary>
  162. /// 拼接URL
  163. /// </summary>
  164. /// <param name="host">主机名</param>
  165. /// <param name="remotePath">地址</param>
  166. /// <param name="fileName">文件名</param>
  167. /// <returns>返回完整的URL</returns>
  168. private string UrlCombine(string host, string remotePath, string fileName)
  169. {
  170. string result = new Uri(new Uri(new Uri(host.TrimEnd('/')), remotePath), fileName).ToString(); ;
  171. return result;
  172. }
  173. /// <summary>
  174. /// 创建连接
  175. /// </summary>
  176. /// <param name="url">地址</param>
  177. /// <param name="method">方法</param>
  178. /// <returns>返回 request对象</returns>
  179. private FtpWebRequest CreateConnection(string url, string method)
  180. {
  181. FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
  182. request.Credentials = new NetworkCredential(this.username, this.password);
  183. request.Proxy = this.proxy;
  184. request.KeepAlive = false;
  185. request.UseBinary = useBinary;
  186. request.UsePassive = usePassive;
  187. request.EnableSsl = enableSsl;
  188. request.Method = method;
  189. Console.WriteLine(request);
  190. return request;
  191. }
  192. /// <summary>
  193. /// 上传文件
  194. /// </summary>
  195. /// <param name="localFile">本地文件</param>
  196. /// <param name="remoteFileName">上传文件名</param>
  197. /// <returns>上传成功返回 true</returns>
  198. public bool Upload(FileInfo localFile, string remoteFileName)
  199. {
  200. bool result = false;
  201. if (localFile.Exists)
  202. {
  203. try
  204. {
  205. string url = UrlCombine(Host, RemotePath, remoteFileName);
  206. FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.UploadFile);
  207. using (Stream rs = request.GetRequestStream())
  208. using (FileStream fs = localFile.OpenRead())
  209. {
  210. byte[] buffer = new byte[1024 * 4];
  211. int count = fs.Read(buffer, 0, buffer.Length);
  212. while (count > 0)
  213. {
  214. rs.Write(buffer, 0, count);
  215. count = fs.Read(buffer, 0, buffer.Length);
  216. }
  217. fs.Close();
  218. result = true;
  219. }
  220. }
  221. catch (WebException ex)
  222. {
  223. // MessageBox.Show(ex.Message);
  224. }
  225. return result;
  226. }
  227. // 处理本地文件不存在的情况
  228. return false;
  229. }
  230. /// <summary>
  231. /// 下载文件
  232. /// </summary>
  233. /// <param name="serverName">服务器文件名称</param>
  234. /// <param name="localName">需要保存在本地的文件名称</param>
  235. /// <returns>下载成功返回 true</returns>
  236. public bool Download(string serverName, string localName)
  237. {
  238. bool result = false;
  239. using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate))
  240. {
  241. try
  242. {
  243. string url = UrlCombine(Host, RemotePath, serverName);
  244. Console.WriteLine(url);
  245. FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.DownloadFile);
  246. request.ContentOffset = fs.Length;
  247. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  248. {
  249. fs.Position = fs.Length;
  250. byte[] buffer = new byte[1024 * 4];
  251. int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
  252. while (count > 0)
  253. {
  254. fs.Write(buffer, 0, count);
  255. count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
  256. }
  257. response.GetResponseStream().Close();
  258. }
  259. result = true;
  260. }
  261. catch (WebException ex)
  262. {
  263. // 处理ftp连接中的异常
  264. throw ex;
  265. }
  266. }
  267. return result;
  268. }
  269. //main函数
  270. //static void Main(string[] args)
  271. //{
  272. // FtpHelper ftpHelper = new FtpHelper("ftp://192.168.202.54/", "fileftp", "123456");
  273. // ftpHelper.RemotePath = "fsa/";
  274. // //下载
  275. // //ftpHelper.Download("java.rar", "D:\\java1.rar");
  276. // //上传
  277. // FileInfo fileInfo = new FileInfo("Z:\\A.nc");
  278. // ftpHelper.Upload(fileInfo, "K.txt");
  279. //}
  280. }
  281. }