c# 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);
        }
    }
}

好了,就这样吧!
————————————————
版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011465910/article/details/126563124

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值