FTPClient.cs 10 KB

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