C# FTP操作(上傳、下載等……)

目錄

判斷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,則該參數無效。
————————————————
版權聲明:本文爲CSDN博主「只會搬運的小菜鳥」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u011465910/article/details/126563124

        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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章