当前位置:   article > 正文

C# FTP操作(上传、下载等……)

c# ftp

因为工作中经常涉及到FTP文件的上传和下载,每次有这样的需求时都要重复编写相同的代码,后来干脆整理一个FTPClass,这样不仅方便自己使用,也可以共享给部门其它同事,使用时直接调用就可以了,节省了大家的开发时间。其实这个类网上有很多同样的写法,就算是给自己的博客凑篇文章吧。

目录

判断FTP连接

FTP文件上传

FTP文件下载

删除指定FTP文件

删除指定FTP文件夹

获取FTP上文件夹/文件列表

创建文件夹

获取指定FTP文件大小

更改指定FTP文件名称

移动指定FTP文件

应用示例


判断FTP连接

  1. public bool CheckFtp()
  2. {
  3. try
  4. {
  5. FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  6. // ftp用户名和密码
  7. ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  8. ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
  9. ftprequest.Timeout = 3000;
  10. FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
  11. ftpResponse.Close();
  12. return true;
  13. }
  14. catch (Exception ex)
  15. {
  16. return false;
  17. }
  18. }

FTP文件上传

参数localfile为要上传的本地文件,ftpfile为上传到FTP的文件名称,ProgressBar为显示上传进度的滚动条,适用于WinForm。若应用于控制台程序,只要重写该函数,将参数ProgressBar去掉即可,同时将函数实现里所有涉及ProgressBar的地方都删掉。

  1. public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
  2. {
  3. FileInfo fileInf = new FileInfo(localfile);
  4. FtpWebRequest reqFTP;
  5. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));
  6. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  7. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  8. reqFTP.KeepAlive = false;
  9. reqFTP.UseBinary = true;
  10. reqFTP.ContentLength = fileInf.Length;
  11. if (pb != null)
  12. {
  13. pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
  14. pb.Maximum = pb.Maximum + 1;
  15. pb.Minimum = 0;
  16. pb.Value = 0;
  17. }
  18. int buffLength = 2048;
  19. byte[] buff = new byte[buffLength];
  20. int contentLen;
  21. FileStream fs = fileInf.OpenRead();
  22. try
  23. {
  24. Stream strm = reqFTP.GetRequestStream();
  25. contentLen = fs.Read(buff, 0, buffLength);
  26. while (contentLen != 0)
  27. {
  28. strm.Write(buff, 0, contentLen);
  29. if (pb != null)
  30. {
  31. if (pb.Value != pb.Maximum)
  32. pb.Value = pb.Value + 1;
  33. }
  34. contentLen = fs.Read(buff, 0, buffLength);
  35. System.Windows.Forms.Application.DoEvents();
  36. }
  37. if (pb != null)
  38. pb.Value = pb.Maximum;
  39. System.Windows.Forms.Application.DoEvents();
  40. strm.Close();
  41. fs.Close();
  42. }
  43. catch (Exception ex)
  44. {
  45. throw new Exception(ex.Message);
  46. }
  47. }

FTP文件下载

参数localfilename为将下载到本地的文件名称,ftpfilename为要下载的FTP上文件名称,ProcessBar为用于显示下载进度的进度条。该函数用于WinForm,若用于控制台,只要重写该函数,删除所有涉及ProcessBar的代码即可。

  1. public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
  2. {
  3. long fileSize = GetFileSize(ftpfileName);
  4. if (fileSize > 0)
  5. {
  6. if (pb != null)
  7. {
  8. pb.Maximum = Convert.ToInt32(fileSize / 2048);
  9. pb.Maximum = pb.Maximum + 1;
  10. pb.Minimum = 0;
  11. pb.Value = 0;
  12. }
  13. try
  14. {
  15. FileStream outputStream = new FileStream(localfilename, FileMode.Create);
  16. FtpWebRequest reqFTP;
  17. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
  18. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  19. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  20. reqFTP.UseBinary = true;
  21. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  22. Stream ftpStream = response.GetResponseStream();
  23. int bufferSize = 2048;
  24. int readCount;
  25. byte[] buffer = new byte[bufferSize];
  26. readCount = ftpStream.Read(buffer, 0, bufferSize);
  27. while (readCount > 0)
  28. {
  29. outputStream.Write(buffer, 0, readCount);
  30. if (pb != null)
  31. {
  32. if (pb.Value != pb.Maximum)
  33. pb.Value = pb.Value + 1;
  34. }
  35. readCount = ftpStream.Read(buffer, 0, bufferSize);
  36. System.Windows.Forms.Application.DoEvents();
  37. }
  38. if (pb != null)
  39. pb.Value = pb.Maximum;
  40. System.Windows.Forms.Application.DoEvents();
  41. ftpStream.Close();
  42. outputStream.Close();
  43. response.Close();
  44. }
  45. catch (Exception ex)
  46. {
  47. File.Delete(localfilename);
  48. throw new Exception(ex.Message);
  49. }
  50. }
  51. }

删除指定FTP文件

  1. public void Delete(string fileName)
  2. {
  3. try
  4. {
  5. FtpWebRequest reqFTP;
  6. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
  7. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  8. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  9. reqFTP.KeepAlive = false;
  10. string result = String.Empty;
  11. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  12. long size = response.ContentLength;
  13. Stream datastream = response.GetResponseStream();
  14. StreamReader sr = new StreamReader(datastream);
  15. result = sr.ReadToEnd();
  16. sr.Close();
  17. datastream.Close();
  18. response.Close();
  19. }
  20. catch (Exception ex)
  21. {
  22. throw new Exception(ex.Message);
  23. }
  24. }

删除指定FTP文件夹

  1. public void RemoveDirectory(string urlpath)
  2. {
  3. try
  4. {
  5. string uri = ftpURI + urlpath;
  6. FtpWebRequest reqFTP;
  7. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  8. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  9. reqFTP.KeepAlive = false;
  10. reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
  11. string result = String.Empty;
  12. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  13. long size = response.ContentLength;
  14. Stream datastream = response.GetResponseStream();
  15. StreamReader sr = new StreamReader(datastream);
  16. result = sr.ReadToEnd();
  17. sr.Close();
  18. datastream.Close();
  19. response.Close();
  20. }
  21. catch (Exception ex)
  22. {
  23. throw new Exception(ex.Message);
  24. }
  25. }

获取FTP上文件夹/文件列表

ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。

  1. public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword)
  2. {
  3. List<string> strs = new List<string>();
  4. try
  5. {
  6. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  7. // ftp用户名和密码
  8. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  9. if (Detail)
  10. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  11. else
  12. reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  13. WebResponse response = reqFTP.GetResponse();
  14. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  15. string line = reader.ReadLine();
  16. while (line != null)
  17. {
  18. if (ListType == 1)
  19. {
  20. if (line.Contains("."))
  21. {
  22. if (Keyword.Trim() == "*.*" || Keyword.Trim() == "")
  23. {
  24. strs.Add(line);
  25. }
  26. else if (line.IndexOf(Keyword.Trim()) > -1)
  27. {
  28. strs.Add(line);
  29. }
  30. }
  31. }
  32. else if (ListType == 2)
  33. {
  34. if (!line.Contains("."))
  35. {
  36. if (Keyword.Trim() == "*" || Keyword.Trim() == "")
  37. {
  38. strs.Add(line);
  39. }
  40. else if (line.IndexOf(Keyword.Trim()) > -1)
  41. {
  42. strs.Add(line);
  43. }
  44. }
  45. }
  46. else if (ListType == 3)
  47. {
  48. strs.Add(line);
  49. }
  50. line = reader.ReadLine();
  51. }
  52. reader.Close();
  53. response.Close();
  54. return strs;
  55. }
  56. catch (Exception ex)
  57. {
  58. throw new Exception(ex.Message);
  59. }
  60. }

创建文件夹

  1. public void MakeDir(string dirName)
  2. {
  3. FtpWebRequest reqFTP;
  4. try
  5. {
  6. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
  7. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  8. reqFTP.UseBinary = true;
  9. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  10. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  11. Stream ftpStream = response.GetResponseStream();
  12. ftpStream.Close();
  13. response.Close();
  14. }
  15. catch (Exception ex)
  16. {
  17. throw new Exception(ex.Message);
  18. }
  19. }

获取指定FTP文件大小

  1. public long GetFileSize(string ftpfileName)
  2. {
  3. long fileSize = 0;
  4. try
  5. {
  6. FtpWebRequest reqFTP;
  7. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
  8. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  9. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  10. reqFTP.UseBinary = true;
  11. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  12. Stream ftpStream = response.GetResponseStream();
  13. fileSize = response.ContentLength;
  14. ftpStream.Close();
  15. response.Close();
  16. }
  17. catch (Exception ex)
  18. {
  19. throw new Exception(ex.Message);
  20. }
  21. return fileSize;
  22. }

更改指定FTP文件名称

  1. public void ReName(string currentFilename, string newFilename)
  2. {
  3. FtpWebRequest reqFTP;
  4. try
  5. {
  6. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
  7. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  8. reqFTP.RenameTo = newFilename;
  9. reqFTP.UseBinary = true;
  10. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  11. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  12. Stream ftpStream = response.GetResponseStream();
  13. ftpStream.Close();
  14. response.Close();
  15. }
  16. catch (Exception ex)
  17. {
  18. throw new Exception(ex.Message);
  19. }
  20. }

移动指定FTP文件

移动FTP文件其实就是重命名文件,只要将目标文件指定一个新的FTP地址就可以了。我没用过,不知道是否可行,因为C++是这么操作的。

  1. public void MovieFile(string currentFilename, string newDirectory)
  2. {
  3. ReName(currentFilename, newDirectory);
  4. }

应用示例

将上面的内容打包到下面这个FTP类中,就可以在你的业务代码中调用了。

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Collections.Generic;
  5. namespace TECSharpFunction
  6. {
  7. /// <summary>
  8. /// FTP操作
  9. /// </summary>
  10. public class FTPHelper
  11. {
  12. #region FTPConfig
  13. string ftpURI;
  14. string ftpUserID;
  15. string ftpServerIP;
  16. string ftpPassword;
  17. string ftpRemotePath;
  18. #endregion
  19. /// <summary>
  20. /// 连接FTP服务器
  21. /// </summary>
  22. /// <param name="FtpServerIP">FTP连接地址</param>
  23. /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
  24. /// <param name="FtpUserID">用户名</param>
  25. /// <param name="FtpPassword">密码</param>
  26. public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
  27. {
  28. ftpServerIP = FtpServerIP;
  29. ftpRemotePath = FtpRemotePath;
  30. ftpUserID = FtpUserID;
  31. ftpPassword = FtpPassword;
  32. ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  33. }
  34. //把上面介绍的那些方法都放到下面
  35. }
  36. }

举个例子:

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Collections.Generic;
  5. uusing TECSharpFunction;
  6. namespace FTPTest
  7. {
  8. public partial class Form1 : Form
  9. {
  10. public Form1()
  11. {
  12. InitializeComponent();
  13. }
  14. Public void FTP_Test()
  15. {
  16. FTPHelper ftpClient = new FTPHelper("192.168.1.1",@"/test","Test","Test");
  17. ftpClient.Download("test.txt", "test1.txt", progressBar1);
  18. }
  19. }
  20. }

好了,就这样吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/199817
推荐阅读
相关标签
  

闽ICP备14008679号