FTPTool.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. string filename = ftpFilePath.Substring(ftpFilePath.LastIndexOf("\\") + 1);
  38. string tmpname = Guid.NewGuid().ToString();
  39. string uri = Path.Combine(ftpURI, ftpFilePath);
  40. if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
  41. FtpWebRequest ftp = GetRequest(uri);
  42. ftp.Method = WebRequestMethods.Ftp.DownloadFile;
  43. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  44. {
  45. using (Stream responseStream = response.GetResponseStream())
  46. {
  47. using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))
  48. {
  49. byte[] buffer = new byte[2048];
  50. int read = 0;
  51. do
  52. {
  53. read = responseStream.Read(buffer, 0, buffer.Length);
  54. fs.Write(buffer, 0, read);
  55. } while (!(read == 0));
  56. fs.Flush();
  57. }
  58. }
  59. }
  60. return false;
  61. }
  62. }
  63. }