FTPClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 TestTool.RemoteTriggerAPP
  10. {
  11. public class FtpState
  12. {
  13. private ManualResetEvent wait;
  14. private FtpWebRequest request;
  15. private string fileName;
  16. private Exception operationException = null;
  17. private FtpStatusCode status;
  18. public FtpState()
  19. {
  20. wait = new ManualResetEvent(false);
  21. }
  22. public ManualResetEvent OperationComplete
  23. {
  24. get { return wait; }
  25. }
  26. public FtpWebRequest Request
  27. {
  28. get { return request; }
  29. set { request = value; }
  30. }
  31. public string FileName
  32. {
  33. get { return fileName; }
  34. set { fileName = value; }
  35. }
  36. public Exception OperationException
  37. {
  38. get { return operationException; }
  39. set { operationException = value; }
  40. }
  41. public FtpStatusCode StatusCode
  42. {
  43. get { return status; }
  44. set { status = value; }
  45. }
  46. }
  47. public class FTPClient
  48. {
  49. public delegate void UploadDataCompletedEventHandler(FtpState state);
  50. public delegate void UploadDataProgressEventHandler(double percent);
  51. public event UploadDataCompletedEventHandler OnUploadSuccessful;
  52. public event UploadDataCompletedEventHandler OnUploadFail;
  53. public event UploadDataProgressEventHandler OnUploadProgress;
  54. private int uploadTimeOut = 5 * 1000 * 60;
  55. public string Host
  56. {
  57. private set; get;
  58. }
  59. public string UesrName
  60. {
  61. private set; get;
  62. }
  63. public string Password
  64. {
  65. private set; get;
  66. }
  67. public int UploadTimeOut
  68. {
  69. get
  70. {
  71. return uploadTimeOut;
  72. }
  73. set
  74. {
  75. uploadTimeOut = value;
  76. }
  77. }
  78. public FTPClient(string host, string usrName, string password)
  79. {
  80. Host = host;
  81. UesrName = usrName;
  82. Password = password;
  83. }
  84. /// <summary>
  85. /// 上傳檔案到FTPServer(斷點續傳)
  86. /// </summary>
  87. /// <param name="uploadFilePath">本地上傳檔案的路徑</param>
  88. /// <param name="uploadFtpPath">FTPServer上的存放路徑</param>
  89. public bool FtpUploadBroken(string uploadFilePath, string uploadFtpPath)
  90. {
  91. if (uploadFtpPath == null)
  92. {
  93. uploadFtpPath = "";
  94. }
  95. string newFileName = string.Empty;
  96. bool success = true;
  97. FileInfo fileInf = new FileInfo(uploadFilePath);
  98. long allbye = (long)fileInf.Length;
  99. long startfilesize = GetFileSize(uploadFtpPath);
  100. if (startfilesize >= allbye)
  101. {
  102. return true;
  103. }
  104. long startbye = startfilesize;
  105. FtpWebRequest reqFTP;
  106. // 根据uri创建FtpWebRequest对象
  107. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadFtpPath));
  108. // ftp用户名和密码
  109. reqFTP.Credentials = new NetworkCredential(UesrName, Password);
  110. // 默认为true,连接不会被关闭
  111. // 在一个命令之后被执行
  112. reqFTP.KeepAlive = false;
  113. // 指定执行什么命令
  114. reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
  115. // 指定数据传输类型
  116. reqFTP.UseBinary = true;
  117. // 上传文件时通知服务器文件的大小
  118. reqFTP.ContentLength = fileInf.Length;
  119. reqFTP.EnableSsl = true;
  120. int buffLength = 2048000;// 缓冲大小设置为200kb
  121. byte[] buff = new byte[buffLength];
  122. // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
  123. using (FileStream fs = fileInf.OpenRead())
  124. {
  125. Stream strm = null;
  126. try
  127. {
  128. // 把上传的文件写入流
  129. strm = reqFTP.GetRequestStream();
  130. // 每次读文件流的2kb
  131. fs.Seek(startfilesize, 0);
  132. int contentLen = fs.Read(buff, 0, buffLength);
  133. // 流内容没有结束
  134. while (contentLen != 0)
  135. {
  136. // 把内容从file stream 写入 upload stream
  137. strm.Write(buff, 0, contentLen);
  138. contentLen = fs.Read(buff, 0, buffLength);
  139. startbye += contentLen;
  140. double percent = (double)((decimal)startbye / reqFTP.ContentLength) * 100;
  141. OnUploadProgress?.Invoke(percent);
  142. }
  143. // 关闭两个流
  144. strm.Close();
  145. fs.Close();
  146. }
  147. catch(Exception ex)
  148. {
  149. success = false;
  150. }
  151. finally
  152. {
  153. if (fs != null)
  154. {
  155. fs.Close();
  156. }
  157. if (strm != null)
  158. {
  159. strm.Close();
  160. }
  161. }
  162. }
  163. return success;
  164. }
  165. /// <summary>
  166. /// 獲取已上傳檔案大小
  167. /// </summary>
  168. /// <param name="remoteFilepath">服务器文件路径</param>
  169. /// <returns></returns>
  170. private long GetFileSize(string remoteFilepath)
  171. {
  172. long filesize = 0;
  173. try
  174. {
  175. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  176. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(remoteFilepath);
  177. reqFTP.EnableSsl = true;
  178. reqFTP.KeepAlive = false;
  179. reqFTP.UseBinary = true;
  180. reqFTP.Credentials = new NetworkCredential(UesrName, Password);//用户,密码
  181. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  182. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  183. filesize = response.ContentLength;
  184. return filesize;
  185. }
  186. catch(Exception ex)
  187. {
  188. return 0;
  189. }
  190. }
  191. /// <summary>
  192. /// 上傳檔案到FTPServer
  193. /// </summary>
  194. /// <param name="uploadFilePath">本地上傳檔案的路徑</param>
  195. /// <param name="uploadFtpPath">FTPServer上的存放路徑</param>
  196. public void UploadFile(string uploadFilePath, string uploadFtpPath)
  197. {
  198. Uri target = new Uri(uploadFtpPath);
  199. FtpState state = new FtpState();
  200. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
  201. request.Method = WebRequestMethods.Ftp.UploadFile;
  202. request.Credentials = new NetworkCredential(UesrName, Password);
  203. state.Request = request;
  204. state.FileName = uploadFilePath;
  205. // Asynchronously get the stream for the file contents.
  206. request.BeginGetRequestStream(
  207. new AsyncCallback(EndGetStreamCallback),
  208. state
  209. );
  210. ThreadPool.RegisterWaitForSingleObject(state.OperationComplete, new WaitOrTimerCallback(TimeoutCallback), state, UploadTimeOut, true);
  211. }
  212. private void EndGetStreamCallback(IAsyncResult ar)
  213. {
  214. FtpState state = (FtpState)ar.AsyncState;
  215. Stream requestStream = null;
  216. // End the asynchronous call to get the request stream.
  217. try
  218. {
  219. using (requestStream = state.Request.EndGetRequestStream(ar))
  220. {
  221. // Copy the file contents to the request stream.
  222. const int bufferLength = 2048;
  223. byte[] buffer = new byte[bufferLength];
  224. int count = 0;
  225. int readBytes = 0;
  226. using (FileStream stream = File.OpenRead(state.FileName))
  227. {
  228. do
  229. {
  230. readBytes = stream.Read(buffer, 0, bufferLength);
  231. requestStream.Write(buffer, 0, readBytes);
  232. count += readBytes;
  233. }
  234. while (readBytes != 0);
  235. }
  236. Console.WriteLine("Writing {0} bytes to the stream.", count);
  237. // IMPORTANT: Close the request stream before sending the request.
  238. requestStream.Close();
  239. }
  240. // Asynchronously get the response to the upload request.
  241. state.Request.BeginGetResponse(
  242. new AsyncCallback(EndGetResponseCallback),
  243. state
  244. );
  245. }
  246. // Return exceptions to the main application thread.
  247. catch (Exception e)
  248. {
  249. Console.WriteLine("Could not get the request stream.");
  250. state.OperationException = e;
  251. state.OperationComplete.Set();
  252. //if (OnUploadFail != null)
  253. // OnUploadFail(state);
  254. }
  255. }
  256. private void EndGetResponseCallback(IAsyncResult ar)
  257. {
  258. FtpState state = (FtpState)ar.AsyncState;
  259. FtpWebResponse response = null;
  260. try
  261. {
  262. response = (FtpWebResponse)state.Request.EndGetResponse(ar);
  263. response.Close();
  264. state.StatusCode = response.StatusCode;
  265. state.OperationComplete.Set();
  266. }
  267. // Return exceptions to the main application thread.
  268. catch (Exception e)
  269. {
  270. //Console.WriteLine("Error getting response.");
  271. state.OperationException = e;
  272. state.OperationComplete.Set();
  273. //if (OnUploadFail != null)
  274. // OnUploadFail(state);
  275. }
  276. }
  277. private void TimeoutCallback(object state, bool timedOut)
  278. {
  279. FtpState _state = state as FtpState;
  280. if (timedOut)
  281. {
  282. _state.Request.Abort();
  283. if (OnUploadFail != null)
  284. OnUploadFail(_state);
  285. }
  286. else
  287. {
  288. if (_state.StatusCode == FtpStatusCode.ClosingData)
  289. {
  290. if (OnUploadSuccessful != null)
  291. OnUploadSuccessful(_state);
  292. }
  293. else
  294. {
  295. if (OnUploadFail != null)
  296. OnUploadFail(_state);
  297. }
  298. }
  299. }
  300. }
  301. }