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

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

目录

判断FTP连接

FTP文件上传

FTP文件下载

删除指定FTP文件

删除指定FTP文件夹

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

创建文件夹

获取指定FTP文件大小

更改指定FTP文件名称

移动指定FTP文件

应用示例


判断FTP连接

        public bool CheckFtp()
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                // ftp用户名和密码
                ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Timeout = 3000;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();

                ftpResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

FTP文件上传

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

        public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
        {
            FileInfo fileInf = new FileInfo(localfile);
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            if (pb != null)
            {
                pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
                pb.Maximum = pb.Maximum + 1;
                pb.Minimum = 0;
                pb.Value = 0;
            }
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    if (pb != null)
                    {
                        if (pb.Value != pb.Maximum)
                            pb.Value = pb.Value + 1;
                    }
                    contentLen = fs.Read(buff, 0, buffLength);
                    System.Windows.Forms.Application.DoEvents();
                }
                if (pb != null)
                    pb.Value = pb.Maximum;
                System.Windows.Forms.Application.DoEvents();
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

FTP文件下载

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

        public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
        {
            long fileSize = GetFileSize(ftpfileName);
            if (fileSize > 0)
            {
                if (pb != null)
                {
                    pb.Maximum = Convert.ToInt32(fileSize / 2048);
                    pb.Maximum = pb.Maximum + 1;
                    pb.Minimum = 0;
                    pb.Value = 0;
                }
                try
                {
                    FileStream outputStream = new FileStream(localfilename, FileMode.Create);
                    FtpWebRequest reqFTP;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    int bufferSize = 2048;
                    
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        if (pb != null)
                        {
                            if (pb.Value != pb.Maximum)
                                pb.Value = pb.Value + 1;
                        }
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        System.Windows.Forms.Application.DoEvents();
                    }
                    if (pb != null)
                        pb.Value = pb.Maximum;
                    System.Windows.Forms.Application.DoEvents();
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                }
                catch (Exception ex)
                {
                    File.Delete(localfilename);
                    throw new Exception(ex.Message);
                }
            }
        }

删除指定FTP文件

        public void Delete(string fileName)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.KeepAlive = false;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

删除指定FTP文件夹

        public void RemoveDirectory(string urlpath)
        {
            try
            {
                string uri = ftpURI + urlpath;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

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

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

        public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword)
        {
            List<string> strs = new List<string>();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                if (Detail)
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                else
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (ListType == 1)
                    {
                        if (line.Contains("."))
                        {
                            if (Keyword.Trim() == "*.*" || Keyword.Trim() == "")
                            {
                                strs.Add(line);
                            }
                            else if (line.IndexOf(Keyword.Trim()) > -1)
                            {
                                strs.Add(line);
                            }
                        }
                    }
                    else if (ListType == 2)
                    {
                        if (!line.Contains("."))
                        {
                            if (Keyword.Trim() == "*" || Keyword.Trim() == "")
                            {
                                strs.Add(line);
                            }
                            else if (line.IndexOf(Keyword.Trim()) > -1)
                            {
                                strs.Add(line);
                            }
                        }
                    }
                    else if (ListType == 3)
                    {
                        strs.Add(line);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

创建文件夹

        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

获取指定FTP文件大小

        public long GetFileSize(string ftpfileName)
        {
            long fileSize = 0;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return fileSize;
        }

更改指定FTP文件名称

        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

移动指定FTP文件

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

        public void MovieFile(string currentFilename, string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }

应用示例

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

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;

namespace TECSharpFunction
{
    /// <summary>
    /// FTP操作
    /// </summary>
    public class FTPHelper
    {
        #region FTPConfig
        string ftpURI;
        string ftpUserID;
        string ftpServerIP;
        string ftpPassword;
        string ftpRemotePath;
        #endregion

        /// <summary>  
        /// 连接FTP服务器
        /// </summary>  
        /// <param name="FtpServerIP">FTP连接地址</param>  
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
        /// <param name="FtpUserID">用户名</param>  
        /// <param name="FtpPassword">密码</param>  
        public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

        //把上面介绍的那些方法都放到下面

    }
}

举个例子:

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
uusing TECSharpFunction;

namespace FTPTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        Public void FTP_Test()
        {
            FTPHelper ftpClient = new FTPHelper("192.168.1.1",@"/test","Test","Test");
            ftpClient.Download("test.txt", "test1.txt", progressBar1);
        }
    }
}

好了,就这样吧!

  • 27
    点赞
  • 144
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只会搬运的小菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值