C#隐式FTPS (Implicit FTPS)

时间:2021-12-21 03:43:46

實現的方式是通過第三方程式庫實現的,當然最主要的是開源且免費,已測試過沒有問題!

目前還沒有直接取得目錄FileInfo list的方法,不過還好可以用GetDirectoryList來取得類似的結果。

可以參考 https://ftps.codeplex.com/

public class ImplicitFtps
    {
        private static readonly string hostName = "199.1*3.***.**";
        private static readonly string userName = "OECRT";
        private static readonly string password = "****";
        private static readonly int port = 1051;


        public FTPSClient Connect()
        {
            FTPSClient client = new FTPSClient();
            client.Connect(hostName, port,
                                      new NetworkCredential(userName, password),
                                      ESSLSupportMode.Implicit,
                                      new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }),
                                      null,
                                      0,
                                      0,
                                      0,
                                      120000,
                                      false,
                                      EDataConnectionMode.Passive);
            return client;
        }


        public void UploadFile(string localFile, string remotePath)
        {   
            using (FTPSClient client = this.Connect())
            {
                if (string.IsNullOrEmpty(remotePath))
                    remotePath = client.GetCurrentDirectory();

                client.SetTransferMode(ETransferMode.Binary);
                client.SetTextEncoding(ETextEncoding.UTF8);
                FileInfo fileInfo = new FileInfo(localFile);
                client.PutFile(localFile, System.IO.Path.Combine(remotePath, fileInfo.Name));
            }
        }

        public IList<DirectoryListItem> GetFiles()
        {
            using (FTPSClient client = this.Connect())
            {
                return client.GetDirectoryList();
            }
        }
    }