【C#】工具類-FTP操作封裝類FTPHelper

来源:https://www.cnblogs.com/zhangwc/archive/2020/01/09/12170769.html
-Advertisement-
Play Games

C# FTPHelper實現FTP伺服器文件讀寫操作,支持SSL協議(FTP伺服器為:Serv-U10.0)。 SSL測試調用代碼 任何地方如有紕漏,歡迎諸位道友指教。 ...


C# FTPHelper實現FTP伺服器文件讀寫操作,支持SSL協議(FTP伺服器為:Serv-U10.0)。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace FTPTest
{
    public class FTPHelper
    {
        #region 變數
        /// <summary>
        /// FTP請求對象
        /// </summary>
        FtpWebRequest request = null;
        /// <summary>
        /// FTP響應對象
        /// </summary>
        FtpWebResponse response = null;

        /// <summary>
        /// FTP伺服器長地址
        /// </summary>
        public string FtpURI { get; private set; }
        /// <summary>
        /// FTP伺服器IP
        /// </summary>
        public string ServerIP { get; private set; }
        /// <summary>
        /// FTP埠
        /// </summary>
        public int ServerPort { get; private set; }
        /// <summary>
        /// FTP用戶
        /// </summary>
        public string Username { get; private set; }
        /// <summary>
        /// FTP密碼
        /// </summary>
        public string Password { get; private set; }
        /// <summary>
        /// 是否啟用SSL
        /// </summary>
        public bool EnableSsl { get; private set; }
        #endregion

        #region 構造
        /// <summary>  
        /// 初始化
        /// </summary>  
        /// <param name="FtpServerIP">IP</param> 
        /// <param name="ftpServerPort"></param> 
        /// <param name="FtpUserID">用戶名</param> 
        /// <param name="FtpPassword">密碼</param> 
        public FTPHelper(string ftpServerIP, int ftpServerPort, string ftpUsername, string ftpPassword, bool ftpEnableSsl = false)
        {
            ServerIP = ftpServerIP;
            ServerPort = ftpServerPort;
            Username = ftpUsername;
            Password = ftpPassword;
            EnableSsl = ftpEnableSsl;
            FtpURI = string.Format("ftp://{0}:{1}/", ftpServerIP, ftpServerPort);
        }
        ~FTPHelper()
        {
            if (response != null)
            {
                response.Close();
                response = null;
            }
            if (request != null)
            {
                request.Abort();
                request = null;
            }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 建立FTP鏈接,返迴響應對象
        /// </summary>
        /// <param name="uri">FTP地址</param>
        /// <param name="ftpMethod">操作命令</param>
        private FtpWebResponse Open(Uri uri, string ftpMethod)
        {
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(uri);
                request.Method = ftpMethod;
                request.UseBinary = true;
                request.KeepAlive = false;
                request.UsePassive = true;//被動模式
                request.EnableSsl = EnableSsl;
                request.Credentials = new NetworkCredential(Username, Password);
                request.Timeout = 30000;
                //首次連接FTP Server時,會有一個證書分配過程。
                //根據驗證過程,遠程證書無效。
                ServicePoint sp = request.ServicePoint;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                return (FtpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 建立FTP鏈接,返回請求對象
        /// </summary>
        /// <param name="uri">FTP地址</param>
        /// <param name="ftpMethod">操作命令</param>
        private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)
        {
            try
            {
                request = (FtpWebRequest)WebRequest.Create(uri);
                request.Method = ftpMethod;
                request.UseBinary = true;
                request.KeepAlive = false;
                request.UsePassive = true;//被動模式
                request.EnableSsl = EnableSsl;
                request.Credentials = new NetworkCredential(Username, Password);
                request.Timeout = 30000;

                ServicePoint sp = request.ServicePoint;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                return request;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 證書驗證回調
        /// </summary>
        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        /// <summary>
        /// 下載文件
        /// </summary>
        /// <param name="remoteFileName">遠程文件</param>
        /// <param name="localFileName">本地文件</param>
        public bool Get(string remoteFileName, string localFileName)
        {
            response = Open(new Uri(FtpURI + remoteFileName), WebRequestMethods.Ftp.DownloadFile);
            if (response == null) return false;

            try
            {
                using (FileStream outputStream = new FileStream(localFileName, FileMode.Create))
                {
                    using (Stream ftpStream = response.GetResponseStream())
                    {
                        long length = response.ContentLength;
                        int bufferSize = 2048;
                        int readCount;
                        byte[] buffer = new byte[bufferSize];
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 文件上傳
        /// </summary>
        /// <param name="localFileName">本地文件</param>
        /// <param name="localFileName">遠程文件</param>
        public bool Put(string localFileName, string remoteFileName)
        {
            FileInfo fi = new FileInfo(localFileName);
            if (fi.Exists == false) return false;
            request = OpenRequest(new Uri(FtpURI + remoteFileName), WebRequestMethods.Ftp.UploadFile);
            if (request == null) return false;

            request.ContentLength = fi.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            try
            {
                using (var fs = fi.OpenRead())
                {
                    using (var strm = request.GetRequestStream())
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        while (contentLen != 0)
                        {
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 刪除文件
        /// </summary>
        public bool DeleteFile(string fileName)
        {
            response = Open(new Uri(FtpURI + fileName), WebRequestMethods.Ftp.DeleteFile);
            return response == null ? false : true;
        }

        /// <summary>
        /// 創建目錄
        /// </summary>
        public bool CreateDirectory(string dirName)
        {
            response = Open(new Uri(FtpURI + dirName), WebRequestMethods.Ftp.MakeDirectory);
            return response == null ? false : true;
        }
        /// <summary>
        /// 刪除目錄(包括下麵所有子目錄和子文件)
        /// </summary>
        public bool DeleteDirectory(string dirName)
        {
            var listAll = GetDirectoryAndFiles(dirName);
            if (listAll == null) return false;

            foreach (var m in listAll)
            {
                if (m.IsDirectory)
                    DeleteDirectory(m.Path);
                else
                    DeleteFile(m.Path);
            }
            response = Open(new Uri(FtpURI + dirName), WebRequestMethods.Ftp.RemoveDirectory);
            return response == null ? false : true;
        }

        /// <summary>
        /// 獲取目錄的文件和一級子目錄信息
        /// </summary>
        public List<FileStruct> GetDirectoryAndFiles(string dirName)
        {
            var fileList = new List<FileStruct>();
            response = Open(new Uri(FtpURI + dirName), WebRequestMethods.Ftp.ListDirectoryDetails);
            if (response == null) return fileList;

            try
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream, Encoding.Default))
                    {
                        string line = null;
                        while ((line = sr.ReadLine()) != null)
                        {
                            //line的格式如下:serv-u(文件夾為第1位為d)
                            //drw-rw-rw-   1 user     group           0 Jun 10  2019 BStatus
                            //-rw-rw-rw-   1 user     group         625 Dec  7  2018 FTP文檔.txt
                            string[] arr = line.Split(' ');
                            if (arr.Length < 12) continue;//remotePath不為空時,第1行返回值為:total 10715

                            var model = new FileStruct()
                            {
                                IsDirectory = line.Substring(0, 3) == "drw" ? true : false,
                                Name = arr[arr.Length - 1],
                                Path = dirName + "/" + arr[arr.Length - 1]
                            };

                            if (model.Name != "." && model.Name != "..")//排除.和..
                            {
                                fileList.Add(model);
                            }
                        }
                    }
                }
                return fileList;
            }
            catch
            {
                return fileList;
            }
        }
        /// <summary>
        /// 獲取目錄的文件
        /// </summary>
        public List<FileStruct> GetFiles(string dirName)
        {
            var fileList = new List<FileStruct>();
            response = Open(new Uri(FtpURI + dirName), WebRequestMethods.Ftp.ListDirectory);
            if (response == null) return fileList;

            try
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream, Encoding.Default))
                    {
                        string line = null;
                        while ((line = sr.ReadLine()) != null)
                        {
                            var model = new FileStruct()
                            {
                                Name = line,
                                Path = dirName + "/" + line
                            };
                            fileList.Add(model);
                        }
                    }
                }
                return fileList;
            }
            catch
            {
                return fileList;
            }
        }

        /// <summary>
        /// 獲得遠程文件大小
        /// </summary>
        public long GetFileSize(string fileName)
        {
            response = Open(new Uri(FtpURI + fileName), WebRequestMethods.Ftp.GetFileSize);
            return response == null ? -1 : response.ContentLength;
        }
        /// <summary>
        /// 文件是否存在
        /// </summary>
        public bool FileExist(string fileName)
        {
            long length = GetFileSize(fileName);
            return length == -1 ? false : true;
        }
        /// <summary>
        /// 目錄是否存在
        /// </summary>
        public bool DirectoryExist(string dirName)
        {
            var list = GetDirectoryAndFiles(Path.GetDirectoryName(dirName));
            return list.Count(m => m.IsDirectory == true && m.Name == dirName) > 0 ? true : false;
        }
        /// <summary>
        /// 更改目錄或文件名
        /// </summary>
        /// <param name="oldName">老名稱</param>
        /// <param name="newName">新名稱</param>
        public bool ReName(string oldName, string newName)
        {
            request = OpenRequest(new Uri(FtpURI + oldName), WebRequestMethods.Ftp.Rename);
            request.RenameTo = newName;
            try
            {
                response = (FtpWebResponse)request.GetResponse();
                return response == null ? false : true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }

    /// <summary>
    /// FTP文件類
    /// </summary>
    public class FileStruct
    {
        /// <summary>
        /// 是否為目錄
        /// </summary>
        public bool IsDirectory { get; set; }
        /// <summary>
        /// 創建時間(FTP上無法獲得時間)
        /// </summary>
        //public DateTime CreateTime { get; set; }
        /// <summary>
        /// 文件或目錄名稱
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 路徑
        /// </summary>
        public string Path { get; set; }
    }
}

SSL測試調用代碼

var ftp = new FTPHelper("192.168.0.36", 21, "test", "1", true);
var list = ftp.GetFiles("");

任何地方如有紕漏,歡迎諸位道友指教。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 上一小節,主要介紹了構建最小級別的安裝包,這個安裝包所做的事情很簡單,主要是打包好一些文件,然後放到用戶機器的某個位置下麵。 這個小節,主要是說安裝過程的各種行為如何使用Wix編寫。 CustomAction 1. 使用內建元素 CustomAction 註意到我們之前給用戶安裝過一個文件 Foob ...
  • 我們可以通過使用DataTime這個類來獲取當前的時間。通過調用類中的各種方法我們可以獲取不同的時間:如:日期(2019-01-09)、時間(16:02:12)、日期+時間(2019-01-09 16:11:10)等。 1.獲取日期和時間 DateTime.Now.ToString(); // 20 ...
  • 本筆記摘抄自:https://www.cnblogs.com/PatrickLiu/p/7567880.html,記錄一下學習過程以備後續查用。 一、引言 接上一篇C#設計模式學習筆記:簡單工廠模式(工廠方法模式前奏篇),通過簡單工廠模式的瞭解,它的缺點就是隨著需求的變化我們要不停地修改工廠里 面的 ...
  • 在MVC的Global.asax Application_Error 中處理全局錯誤。判斷為Ajax請求時,我們返回Json對象字元串。不是Ajax請求時,轉到錯誤顯示頁面。 ...
  • 轉載於:https://www.cnblogs.com/nozer1993/p/9042085.html1.安裝 core和netFramework其實是相對獨立的,但是core的IDE是在vs2017才開始支持,而vs2017的安裝環境必須搭配.net4.6,所以: Step1:安裝.net4.6 ...
  • 在MVC中定義自己的許可權特性。在處理未通過許可權的時候,判斷當前請求是否為Ajax請求,如果是Ajax請求,返回Json {state=-1,msg="請登錄"},如過不是Ajax請求那麼就直接重定向到登錄頁面。 ...
  • 簡介 surging 經過兩年多的研發,微服務引擎已經略有雛形,也承蒙各位的厚愛, GitHub上收穫了將近2800星,fork 811,付費用戶企業也有十幾家,還有咨詢培訓, 在2020年,我們將依靠社區的力量,去完善社區版本,更會花更多的精力去維護好付費用戶,大家一起把surging 的社區建設 ...
  • gRpc 官網 鏈接 新建服務端項目 在服務端內先編寫一個 .proto 文件 greet.proto syntax = "proto3"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message H ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...