FTPHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. namespace Y.Utils.NetworkUtils
  5. {
  6. /// <summary>
  7. /// FTP 帮助类
  8. /// </summary>
  9. public class FtpHelper
  10. {
  11. private string ftpHostIP { get; set; }
  12. private string username { get; set; }
  13. private string password { get; set; }
  14. private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } }
  15. public FtpHelper(string ftpHostIP, string username, string password)
  16. {
  17. this.ftpHostIP = ftpHostIP;
  18. this.username = username;
  19. this.password = password;
  20. }
  21. private FtpWebRequest GetRequest(string URI)
  22. {
  23. //根据服务器信息FtpWebRequest创建类的对象
  24. FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);
  25. result.Credentials = new NetworkCredential(username, password);
  26. result.KeepAlive = false;
  27. result.UsePassive = false;
  28. result.UseBinary = true;
  29. return result;
  30. }
  31. public bool DownloadFile(string ftpFilePath, string saveDir)
  32. {
  33. string filename = ftpFilePath.Substring(ftpFilePath.LastIndexOf("\\") + 1);
  34. string tmpname = Guid.NewGuid().ToString();
  35. string uri = Path.Combine(ftpURI, ftpFilePath);
  36. if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
  37. FtpWebRequest ftp = GetRequest(uri);
  38. ftp.Method = WebRequestMethods.Ftp.DownloadFile;
  39. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  40. {
  41. using (Stream responseStream = response.GetResponseStream())
  42. {
  43. using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))
  44. {
  45. byte[] buffer = new byte[2048];
  46. int read = 0;
  47. do
  48. {
  49. read = responseStream.Read(buffer, 0, buffer.Length);
  50. fs.Write(buffer, 0, read);
  51. } while (!(read == 0));
  52. fs.Flush();
  53. }
  54. }
  55. }
  56. return false;
  57. }
  58. }
  59. }