12.4 C井实现FTP下载文件

C# FTP下载文件

  1. // FTP 下载
  2. private int FtpFileDownload(string savePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
  3. {
  4. string ftpServerPath = "ftp://" + ftpServerIP + ":23" + fileName; //":23"指定的端口,不填默认端口为21
  5. string ftpUser = ftpUserID;
  6. string ftpPwd = ftpPassword;
  7. string saveFilePath = savePath;
  8. FileStream outputStream = null;
  9. FtpWebResponse response = null;
  10. FtpWebRequest reqFTP;
  11. try
  12. {
  13. outputStream = new FileStream(saveFilePath, FileMode.Create);
  14. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath));
  15. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  16. reqFTP.UseBinary = true;
  17. reqFTP.KeepAlive = false;
  18. reqFTP.Timeout = 3000;
  19. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  20. response = (FtpWebResponse)reqFTP.GetResponse();
  21. Stream ftpStream = response.GetResponseStream();
  22. int bufferSize = 2048;
  23. int readCount;
  24. ftpFileReadSize = 0;
  25. byte[] buffer = new byte[bufferSize];
  26. readCount = ftpStream.Read(buffer, 0, bufferSize);
  27. while (readCount > 0)
  28. {
  29. ftpFileReadSize += readCount;
  30. outputStream.Write(buffer, 0, readCount);
  31. readCount = ftpStream.Read(buffer, 0, bufferSize);
  32. }
  33. ftpStream.Close();
  34. outputStream.Close();
  35. response.Close();
  36. }
  37. catch (Exception ex)
  38. {
  39. Trace.WriteLine("FtpClient异常:" + ex.Message);
  40. if (outputStream != null)
  41. {
  42. outputStream.Close();
  43. }
  44. if (response != null)
  45. {
  46. response.Close();
  47. }
  48. return -1;
  49. }
  50. return 0;
  51. }
  52. // 获取FTP文件大小
  53. private long GetFtpFileSize(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
  54. {
  55. long fileSize = 0;
  56. string ftpServerPath = "ftp://" + ftpServerIP + ":23" + fileName;
  57. string ftpUser = ftpUserID;
  58. string ftpPwd = ftpPassword;
  59. FtpWebResponse response = null;
  60. FtpWebRequest reqFTP;
  61. try
  62. {
  63. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath));
  64. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  65. reqFTP.UseBinary = true;
  66. reqFTP.KeepAlive = false;
  67. reqFTP.Timeout = 3000;
  68. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  69. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;//要求返回文件大小属性
  70. response = (FtpWebResponse)reqFTP.GetResponse();
  71. fileSize = response.ContentLength;
  72. response.Close();
  73. }
  74. catch (Exception ex)
  75. {
  76. Trace.WriteLine("FtpClient异常:" + ex.Message);
  77. if (response != null)
  78. {
  79. response.Close();
  80. }
  81. return -1;
  82. }
  83. return fileSize;
  84. }