FTPClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. int buffLength = 2048000;// 缓冲大小设置为200kb
  120. byte[] buff = new byte[buffLength];
  121. // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
  122. using (FileStream fs = fileInf.OpenRead())
  123. {
  124. Stream strm = null;
  125. try
  126. {
  127. // 把上传的文件写入流
  128. strm = reqFTP.GetRequestStream();
  129. // 每次读文件流的2kb
  130. fs.Seek(startfilesize, 0);
  131. int contentLen = fs.Read(buff, 0, buffLength);
  132. // 流内容没有结束
  133. while (contentLen != 0)
  134. {
  135. // 把内容从file stream 写入 upload stream
  136. strm.Write(buff, 0, contentLen);
  137. contentLen = fs.Read(buff, 0, buffLength);
  138. startbye += contentLen;
  139. double percent = (double)((decimal)startbye / reqFTP.ContentLength) * 100;
  140. OnUploadProgress?.Invoke(percent);
  141. }
  142. // 关闭两个流
  143. strm.Close();
  144. fs.Close();
  145. }
  146. catch(Exception ex)
  147. {
  148. success = false;
  149. }
  150. finally
  151. {
  152. if (fs != null)
  153. {
  154. fs.Close();
  155. }
  156. if (strm != null)
  157. {
  158. strm.Close();
  159. }
  160. }
  161. }
  162. return success;
  163. }
  164. /// <summary>
  165. /// 獲取已上傳檔案大小
  166. /// </summary>
  167. /// <param name="remoteFilepath">服务器文件路径</param>
  168. /// <returns></returns>
  169. private long GetFileSize(string remoteFilepath)
  170. {
  171. long filesize = 0;
  172. try
  173. {
  174. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(remoteFilepath);
  175. reqFTP.KeepAlive = false;
  176. reqFTP.UseBinary = true;
  177. reqFTP.Credentials = new NetworkCredential(UesrName, Password);//用户,密码
  178. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  179. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  180. filesize = response.ContentLength;
  181. return filesize;
  182. }
  183. catch
  184. {
  185. return 0;
  186. }
  187. }
  188. /// <summary>
  189. /// 上傳檔案到FTPServer
  190. /// </summary>
  191. /// <param name="uploadFilePath">本地上傳檔案的路徑</param>
  192. /// <param name="uploadFtpPath">FTPServer上的存放路徑</param>
  193. public void UploadFile(string uploadFilePath, string uploadFtpPath)
  194. {
  195. Uri target = new Uri(uploadFtpPath);
  196. FtpState state = new FtpState();
  197. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
  198. request.Method = WebRequestMethods.Ftp.UploadFile;
  199. request.Credentials = new NetworkCredential(UesrName, Password);
  200. state.Request = request;
  201. state.FileName = uploadFilePath;
  202. // Asynchronously get the stream for the file contents.
  203. request.BeginGetRequestStream(
  204. new AsyncCallback(EndGetStreamCallback),
  205. state
  206. );
  207. ThreadPool.RegisterWaitForSingleObject(state.OperationComplete, new WaitOrTimerCallback(TimeoutCallback), state, UploadTimeOut, true);
  208. }
  209. private void EndGetStreamCallback(IAsyncResult ar)
  210. {
  211. FtpState state = (FtpState)ar.AsyncState;
  212. Stream requestStream = null;
  213. // End the asynchronous call to get the request stream.
  214. try
  215. {
  216. using (requestStream = state.Request.EndGetRequestStream(ar))
  217. {
  218. // Copy the file contents to the request stream.
  219. const int bufferLength = 2048;
  220. byte[] buffer = new byte[bufferLength];
  221. int count = 0;
  222. int readBytes = 0;
  223. using (FileStream stream = File.OpenRead(state.FileName))
  224. {
  225. do
  226. {
  227. readBytes = stream.Read(buffer, 0, bufferLength);
  228. requestStream.Write(buffer, 0, readBytes);
  229. count += readBytes;
  230. }
  231. while (readBytes != 0);
  232. }
  233. Console.WriteLine("Writing {0} bytes to the stream.", count);
  234. // IMPORTANT: Close the request stream before sending the request.
  235. requestStream.Close();
  236. }
  237. // Asynchronously get the response to the upload request.
  238. state.Request.BeginGetResponse(
  239. new AsyncCallback(EndGetResponseCallback),
  240. state
  241. );
  242. }
  243. // Return exceptions to the main application thread.
  244. catch (Exception e)
  245. {
  246. Console.WriteLine("Could not get the request stream.");
  247. state.OperationException = e;
  248. state.OperationComplete.Set();
  249. //if (OnUploadFail != null)
  250. // OnUploadFail(state);
  251. }
  252. }
  253. private void EndGetResponseCallback(IAsyncResult ar)
  254. {
  255. FtpState state = (FtpState)ar.AsyncState;
  256. FtpWebResponse response = null;
  257. try
  258. {
  259. response = (FtpWebResponse)state.Request.EndGetResponse(ar);
  260. response.Close();
  261. state.StatusCode = response.StatusCode;
  262. state.OperationComplete.Set();
  263. }
  264. // Return exceptions to the main application thread.
  265. catch (Exception e)
  266. {
  267. //Console.WriteLine("Error getting response.");
  268. state.OperationException = e;
  269. state.OperationComplete.Set();
  270. //if (OnUploadFail != null)
  271. // OnUploadFail(state);
  272. }
  273. }
  274. private void TimeoutCallback(object state, bool timedOut)
  275. {
  276. FtpState _state = state as FtpState;
  277. if (timedOut)
  278. {
  279. _state.Request.Abort();
  280. if (OnUploadFail != null)
  281. OnUploadFail(_state);
  282. }
  283. else
  284. {
  285. if (_state.StatusCode == FtpStatusCode.ClosingData)
  286. {
  287. if (OnUploadSuccessful != null)
  288. OnUploadSuccessful(_state);
  289. }
  290. else
  291. {
  292. if (OnUploadFail != null)
  293. OnUploadFail(_state);
  294. }
  295. }
  296. }
  297. }
  298. }