FTPTool.cs 2.6 KB

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