Tags

, , ,

之前一个项目用到的FTP客户端,支持隐式TLS加密,使用的是AlexPilotti的库 可以通过

public FtpsClient(string server, string remoteUploadPath, string remoteDownLoadPath,
    string userID, string password, bool acceptAllCertificate,bool useImpicit)

来指定FTP的连接属性 如果要想访问的FTP站点证书是自签名的,可以直接指定

acceptAllCertificate = true

来跳过证书验证,具体的加密设置在构造函数中也可以修改

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using AlexPilotti.FTPS.Client;
using AlexPilotti.FTPS.Common;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
namespace Ftp
{
    public class FtpsClient
    {
        string ftpServer;
        string ftpRemoteUploadPath;
        string ftpRemoteDownloadPath;
        string ftpUserID;
        string ftpPassword;
         bool  ftpAcceptAllCertificate;
         bool ftpUseImpicit;
         ESSLSupportMode sslMode;

         public FtpsClient(string server, string remoteUploadPath, string remoteDownLoadPath, string userID, string password, bool acceptAllCertificate,bool useImpicit)
         {
             ftpServer = server;
             ftpRemoteUploadPath = remoteUploadPath.TrimEnd('') + "";
             ftpRemoteDownloadPath = remoteDownLoadPath.TrimEnd('') + "";
             ftpUserID = userID;
             ftpPassword = password;
             ftpAcceptAllCertificate = acceptAllCertificate;
             ftpUseImpicit = useImpicit;
             if (ftpUseImpicit)
             {
                 sslMode = ESSLSupportMode.CredentialsRequired | ESSLSupportMode.Implicit;
             }
             else
             {
                 sslMode = ESSLSupportMode.CredentialsRequired;
             }
         }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="filename">本地文件路径</param>
        public void Upload(string localFilePath)
        {
            try
            {
                using (FTPSClient client = new FTPSClient())
                {

                    // Connect to the server, with mandatory SSL/TLS

                    if (ftpAcceptAllCertificate)
                    {
                        client.Connect(ftpServer,
                                               new NetworkCredential(ftpUserID, ftpPassword),
                                               sslMode,
                                               new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
                    }
                    else
                    {
                        client.Connect(ftpServer,
                                            new NetworkCredential(ftpUserID, ftpPassword),
                                            sslMode);
                    }
                    client.SetTransferMode(ETransferMode.Binary);
                    client.SetTextEncoding(ETextEncoding.UTF8);
                    // Upload a file
                    FileInfo fileInf = new FileInfo(localFilePath);
                    client.PutFile(localFilePath, ftpRemoteUploadPath + fileInf.Name);
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="filePath">本地保存文件路径</param>
        /// <param name="fileName">服务器文件名</param>
        public void Download(string localFilePath, string serverFileName)
        {
            try
            {
                using (FTPSClient client = new FTPSClient())
                {
                    // Connect to the server, with mandatory SSL/TLS
                    if (ftpAcceptAllCertificate)
                    {
                        client.Connect(ftpServer,
                                               new NetworkCredential(ftpUserID, ftpPassword),
                                              sslMode,
                                               new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
                    }
                    else
                    {
                        client.Connect(ftpServer,
                                            new NetworkCredential(ftpUserID, ftpPassword),
                                            sslMode);
                    }
                    client.SetTransferMode(ETransferMode.Binary);
                    client.SetTextEncoding(ETextEncoding.UTF8);
                    // Upload a file
                    client.GetFile(ftpRemoteDownloadPath + serverFileName, localFilePath + serverFileName);
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 获取当前目录下满足指定正则表达式的文件名列表
        /// </summary>
        ///  <param name="regExp">正则表达式</param>
        /// <returns>string[]</returns>
        public IList<string> GetFileList(string regExp)
        {
            try
            {
                using (FTPSClient client = new FTPSClient())
                {
                    // Connect to the server, with mandatory SSL/TLS
                    if (ftpAcceptAllCertificate)
                    {
                        client.Connect(ftpServer,
                                               new NetworkCredential(ftpUserID, ftpPassword),
                                               sslMode,
                                               new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
                    }
                    else
                    {
                        client.Connect(ftpServer,
                                            new NetworkCredential(ftpUserID, ftpPassword),
                                            sslMode);
                    }
                    client.SetTransferMode(ETransferMode.Binary);
                    client.SetTextEncoding(ETextEncoding.UTF8);
                    IList<string> list = client.GetShortDirectoryList(ftpRemoteDownloadPath);
                    IList<string> result = new List<string>();
                    if (regExp.Length != 0)
                    {
                        Regex rg = new Regex(regExp);
                        foreach (var s in list)
                        {
                            if (rg.Match(s).Value != "" && rg.Match(s).Value != null)
                            {
                                result.Add(rg.Match(s).Value);
                            }
                        }
                    }
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        ///  测试FTP服务器连接
        /// </summary>
        public string test()
        {
            try
            {
                IList<string> result = new List<string>();
                using (FTPSClient client = new FTPSClient())
                {
                    // Connect to the server, with mandatory SSL/TLS
                    if (ftpAcceptAllCertificate)
                    {
                        client.Connect(ftpServer,
                                               new NetworkCredential(ftpUserID, ftpPassword),
                                               sslMode,
                                               new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
                    }
                    else
                    {
                        client.Connect(ftpServer,
                                            new NetworkCredential(ftpUserID, ftpPassword),
                                            sslMode);
                    }
                    result = client.GetShortDirectoryList(ftpRemoteDownloadPath);
                }
                string resultString = "";
                foreach (var s in result)
                {
                    resultString += (s + 'n');
                }
                return "FTP访问成功! 当前目录:n" + resultString;
            }
            catch (Exception ex)
            {
                return "FTP访问失败:" + ex.Message;
            }
        }

    }
}