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

时间:2025-03-24 14:49:00

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

目录

判断FTP连接

FTP文件上传

FTP文件下载

删除指定FTP文件

删除指定FTP文件夹

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

创建文件夹

获取指定FTP文件大小

更改指定FTP文件名称

移动指定FTP文件

应用示例


判断FTP连接

        public bool CheckFtp()
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)(new Uri(ftpURI));
                // ftp用户名和密码
                 = new NetworkCredential(ftpUserID, ftpPassword);
                 = ;
                 = 3000;
                FtpWebResponse ftpResponse = (FtpWebResponse)();

                ();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

FTP文件上传

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

        public void Upload(string localfile, string ftpfile,  pb)
        {
            FileInfo fileInf = new FileInfo(localfile);
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)(new Uri(ftpURI + ftpfile));
             = new NetworkCredential(ftpUserID, ftpPassword);
             = ;
             = false;
             = true;
             = ;
            if (pb != null)
            {
                 = Convert.ToInt32( / 2048);
                 =  + 1;
                 = 0;
                 = 0;
            }
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = ();
            try
            {
                Stream strm = ();
                contentLen = (buff, 0, buffLength);
                while (contentLen != 0)
                {
                    (buff, 0, contentLen);
                    if (pb != null)
                    {
                        if ( != )
                             =  + 1;
                    }
                    contentLen = (buff, 0, buffLength);
                    ();
                }
                if (pb != null)
                     = ;
                ();
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

FTP文件下载

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

        public void Download(string localfilename, string ftpfileName,  pb)
        {
            long fileSize = GetFileSize(ftpfileName);
            if (fileSize > 0)
            {
                if (pb != null)
                {
                     = Convert.ToInt32(fileSize / 2048);
                     =  + 1;
                     = 0;
                     = 0;
                }
                try
                {
                    FileStream outputStream = new FileStream(localfilename, );
                    FtpWebRequest reqFTP;
                    reqFTP = (FtpWebRequest)(new Uri(ftpURI + ftpfileName));
                     = new NetworkCredential(ftpUserID, ftpPassword);
                     = ;
                     = true;
                    FtpWebResponse response = (FtpWebResponse)();
                    Stream ftpStream = ();
                    int bufferSize = 2048;
                    
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = (buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        (buffer, 0, readCount);
                        if (pb != null)
                        {
                            if ( != )
                                 =  + 1;
                        }
                        readCount = (buffer, 0, bufferSize);
                        ();
                    }
                    if (pb != null)
                         = ;
                    ();
                    ();
                    ();
                    ();
                }
                catch (Exception ex)
                {
                    (localfilename);
                    throw new Exception();
                }
            }
        }

删除指定FTP文件

        public void Delete(string fileName)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)(new Uri(ftpURI + fileName));
                 = new NetworkCredential(ftpUserID, ftpPassword);
                 = ;
                 = false;
                string result = ;
                FtpWebResponse response = (FtpWebResponse)();
                long size = ;
                Stream datastream = ();
                StreamReader sr = new StreamReader(datastream);
                result = ();
                ();
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

删除指定FTP文件夹

        public void RemoveDirectory(string urlpath)
        {
            try
            {
                string uri = ftpURI + urlpath;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)(new Uri(uri));
                 = new NetworkCredential(ftpUserID, ftpPassword);
                 = false;
                 = ;
                string result = ;
                FtpWebResponse response = (FtpWebResponse)();
                long size = ;
                Stream datastream = ();
                StreamReader sr = new StreamReader(datastream);
                result = ();
                ();
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

获取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)(new Uri(ftpURI));
                // ftp用户名和密码
                 = new NetworkCredential(ftpUserID, ftpPassword);
                if (Detail)
                     = ;
                else
                     = ;
                WebResponse response = ();
                StreamReader reader = new StreamReader(());//中文文件名
                string line = ();
                while (line != null)
                {
                    if (ListType == 1)
                    {
                        if (("."))
                        {
                            if (() == "*.*" || () == "")
                            {
                                (line);
                            }
                            else if ((()) > -1)
                            {
                                (line);
                            }
                        }
                    }
                    else if (ListType == 2)
                    {
                        if (!("."))
                        {
                            if (() == "*" || () == "")
                            {
                                (line);
                            }
                            else if ((()) > -1)
                            {
                                (line);
                            }
                        }
                    }
                    else if (ListType == 3)
                    {
                        (line);
                    }
                    line = ();
                }
                ();
                ();
                return strs;
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

创建文件夹

        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)(new Uri(ftpURI + dirName));
                 = ;
                 = true;
                 = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)();
                Stream ftpStream = ();
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

获取指定FTP文件大小

        public long GetFileSize(string ftpfileName)
        {
            long fileSize = 0;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)(new Uri(ftpURI + ftpfileName));
                 = new NetworkCredential(ftpUserID, ftpPassword);
                 = ;
                 = true;
                FtpWebResponse response = (FtpWebResponse)();
                Stream ftpStream = ();
                fileSize = ;
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
            return fileSize;
        }

更改指定FTP文件名称

        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)(new Uri(ftpURI + currentFilename));
                 = ;
                 = newFilename;
                 = true;
                 = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)();
                Stream ftpStream = ();
                ();
                ();
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }

移动指定FTP文件

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

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

应用示例

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

using System;
using ;
using ;
using ;

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 ;
using ;
using ;
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");
            ("", "", progressBar1);
        }
    }
}

好了,就这样吧!