Loading

FluentFTP 操作类备份

using FluentFTP;
using HH.Lib.Syslog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace HH.Lib.Ftp
{
    /// <summary>
    /// FTP操作类(FluentFTP封装)
    /// </summary>
    public class FtpHelper
    {
        #region 相关参数
        /// <summary>
        /// FtpClient
        /// </summary>
        private FtpClient ftpClient = null;
        /// <summary>
        /// FTP IP地址(127.0.0.1)
        /// </summary>
        private string strFtpUri = string.Empty;
        /// <summary>
        /// FTP端口
        /// </summary>
        private int intFtpPort = 21;
        /// <summary>
        /// FTP用户名
        /// </summary>
        private string strFtpUserID = string.Empty;
        /// <summary>
        /// FTP密码
        /// </summary>
        private string strFtpPassword = string.Empty;
        /// <summary>
        /// 重试次数
        /// </summary>
        private int intRetryTimes = 3;
        /// <summary>
        /// FTP工作目录
        /// </summary>
        private string _workingDirectory = string.Empty;
        /// <summary>
        /// FTP工作目录
        /// </summary>
        public string WorkingDirectory
        {
            get
            {
                return _workingDirectory;
            }
        }
        #endregion

        protected HH.Lib.Syslog.NLogger logger = null;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ftpConfig">FTP配置封装</param>
        public FtpHelper(FtpConfig ftpConfig)
        {
            this.strFtpUri = ftpConfig.str_FtpUri;
            this.intFtpPort = ftpConfig.int_FtpPort;
            this.strFtpUserID = ftpConfig.str_FtpUserID;
            this.strFtpPassword = ftpConfig.str_FtpPassword;
            this.intRetryTimes = ftpConfig.int_RetryTimes;

            logger = new Lib.Syslog.NLogger();
            //创建ftp客户端
            GetFtpClient();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host">FTP IP地址</param>
        /// <param name="port">FTP端口</param>
        /// <param name="username">FTP用户名</param>
        /// <param name="password">FTP密码</param>
        public FtpHelper(string host, int port, string username, string password)
        {
            strFtpUri = host;
            intFtpPort = port;
            strFtpUserID = username;
            strFtpPassword = password;
            logger = new Lib.Syslog.NLogger();
            //创建ftp客户端
            GetFtpClient();
        }
        #endregion

        #region 创建ftp客户端

        private void GetFtpClient()
        {
            if (CheckPara())
            {
                try
                {
                    ftpClient = new FtpClient(strFtpUri, intFtpPort, strFtpUserID, strFtpPassword);
                    ftpClient.RetryAttempts = intRetryTimes;
                }
                catch (Exception ex)
                {
                    logger.Error("GetFtpClient->创建ftp客户端异常:" + ex.ToString());
                }
            }
        }
        #endregion

        #region 校验参数
        /// <summary>
        /// 校验参数
        /// </summary>
        /// <returns></returns>
        private bool CheckPara()
        {
            bool boolResult = true;

            if (string.IsNullOrEmpty(strFtpUri))
            {
                logger.Error("CheckPara->FtpUri为空");
                return false;
            }
            if (string.IsNullOrEmpty(strFtpUserID))
            {
                logger.Error("CheckPara->FtpUserID为空");
                return false;
            }
            if (string.IsNullOrEmpty(strFtpPassword))
            {
                logger.Error( "CheckPara->FtpPassword为空");
                return false;
            }
            if (intFtpPort == 0 || intFtpPort == int.MaxValue || intFtpPort == int.MinValue)
            {
                logger.Error("CheckPara->intFtpPort异常:" + intFtpPort.ToString());
                return false;
            }
            return boolResult;
        }
        #endregion

        #region FTP是否已连接
        /// <summary>
        /// FTP是否已连接
        /// </summary>
        /// <returns></returns>
        public bool isConnected()
        {
            bool result = false;
            if (ftpClient != null)
            {
                result = ftpClient.IsConnected;
            }
            return result;
        }
        #endregion

        #region 连接FTP
        /// <summary>
        /// 连接FTP
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            bool result = false;
            if (ftpClient != null)
            {
                if (ftpClient.IsConnected)
                {
                    return true;
                }
                else
                {
                    ftpClient.Connect();
                    return true;
                }
            }
            return result;
        }
        #endregion

        #region 断开FTP
        /// <summary>
        /// 断开FTP
        /// </summary>
        public void DisConnect()
        {
            if (ftpClient != null)
            {
                if (ftpClient.IsConnected)
                {
                    ftpClient.Disconnect();
                }
            }
        }
        #endregion

        #region 取得文件或目录列表
        /// <summary>
        /// 取得文件或目录列表
        /// </summary>
        /// <param name="remoteDic">远程目录</param>
        /// <param name="type">类型:file-文件,dir-目录</param>
        /// <returns></returns>
        public List<string> ListDirectory(string remoteDic, string type = "file")
        {
            List<string> list = new List<string>();
            type = type.ToLower();

            try
            {
                if (Connect())
                {
                    FtpListItem[] files = ftpClient.GetListing(remoteDic);
                    foreach (FtpListItem file in files)
                    {
                        if (type == "file")
                        {
                            if (file.Type == FtpFileSystemObjectType.File)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else if (type == "dir")
                        {
                            if (file.Type == FtpFileSystemObjectType.Directory)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else
                        {
                            list.Add(file.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("ListDirectory->取得文件或目录列表 异常:" + ex.ToString());
            }
            finally
            {
                DisConnect();
            }

            return list;
        }
        #endregion

        #region 上传单文件
        /// <summary>
        /// 上传单文件
        /// </summary>
        /// <param name="localPath">本地路径(@"D:\abc.txt")</param>
        /// <param name="remoteDic">远端目录("/test")</param>
        /// <returns></returns>
        public bool UploadFile(string localPath, string remoteDic)
        {
            bool boolResult = false;
            FileInfo fileInfo = null;

            try
            {
                //本地路径校验
                if (!File.Exists(localPath))
                {
                    logger.Error("UploadFile->本地文件不存在:" + localPath);
                    return boolResult;
                }
                else
                {
                    fileInfo = new FileInfo(localPath);
                }
                ////远端路径校验
                //if (string.IsNullOrEmpty(remoteDic))
                //{
                //    remoteDic = "/";
                //}
                //if (!remoteDic.StartsWith("/"))
                //{
                //    remoteDic = "/" + remoteDic;
                //}
                //if (!remoteDic.EndsWith("/"))
                //{
                //    remoteDic += "/";
                //}
                remoteDic = CheckDirPath(remoteDic);

                //拼接远端路径
                remoteDic += fileInfo.Name;

                if (Connect())
                {
                    using (FileStream fs = fileInfo.OpenRead())
                    {
                        //重名覆盖
                        boolResult = ftpClient.Upload(fs, remoteDic, FtpRemoteExists.Overwrite, true) == FtpStatus.Success;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("UploadFile->上传文件 异常:" + ex.ToString() + "|*|localPath:" + localPath);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        #region 上传多文件
        /// <summary>
        /// 上传多文件
        /// </summary>
        /// <param name="localFiles">本地路径列表</param>
        /// <param name="remoteDic">远端目录("/test")</param>
        /// <returns></returns>
        public int UploadFiles(IEnumerable<string> localFiles, string remoteDic)
        {
            int count = 0;
            List<FileInfo> listFiles = new List<FileInfo>();

            if (localFiles == null)
            {
                return 0;
            }

            try
            {
                foreach (string file in localFiles)
                {
                    if (!File.Exists(file))
                    {
                        logger.Error("UploadFiles->本地文件不存在:" + file);
                        continue;
                    }
                    listFiles.Add(new FileInfo(file));
                }

                //远端路径校验
                if (string.IsNullOrEmpty(remoteDic))
                {
                    remoteDic = "/";
                }
                if (!remoteDic.StartsWith("/"))
                {
                    remoteDic = "/" + remoteDic;
                }
                if (!remoteDic.EndsWith("/"))
                {
                    remoteDic += "/";
                }

                if (Connect())
                {
                    if (listFiles.Count > 0)
                    {
                        count = ftpClient.UploadFiles(listFiles, remoteDic, FtpRemoteExists.Overwrite, true);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("UploadFiles->上传文件 异常:" + ex.ToString());
            }
            finally
            {
                DisConnect();
            }

            return count;
        }
        #endregion

        #region 下载单文件
        /// <summary>
        /// 下载单文件
        /// </summary>
        /// <param name="localDic">本地目录(@"D:\test")</param>
        /// <param name="remotePath">远程路径("/test/abc.txt")</param>
        /// <returns></returns>
        public bool DownloadFile(string localDic, string remotePath)
        {
            bool boolResult = false;
            string strFileName = string.Empty;

            try
            {
                //本地目录不存在,则自动创建
                if (!Directory.Exists(localDic))
                {
                    Directory.CreateDirectory(localDic);
                }
                //取下载文件的文件名
                strFileName = Path.GetFileName(remotePath);
                //拼接本地路径
                localDic = Path.Combine(localDic, strFileName);

                if (Connect())
                {
                    boolResult = ftpClient.DownloadFile(localDic, remotePath, FtpLocalExists.Overwrite)==FtpStatus.Success;
                }
            }
            catch (Exception ex)
            {
                logger.Error("DownloadFile->下载文件 异常:" + ex.ToString() + "|*|remotePath:" + remotePath);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        #region 下载多文件
        /// <summary>
        /// 下载多文件
        /// </summary>
        /// <param name="localDic">本地目录(@"D:\test")</param>
        /// <param name="remotePath">远程路径列表</param>
        /// <returns></returns>
        public int DownloadFiles(string localDic, IEnumerable<string> remoteFiles)
        {
            int count = 0;
            if (remoteFiles == null)
            {
                return 0;
            }

            try
            {
                //本地目录不存在,则自动创建
                if (!Directory.Exists(localDic))
                {
                    Directory.CreateDirectory(localDic);
                }

                if (Connect())
                {
                    count = ftpClient.DownloadFiles(localDic, remoteFiles, FtpLocalExists.Overwrite);
                }
            }
            catch (Exception ex)
            {
                logger.Error("DownloadFiles->下载文件 异常:" + ex.ToString());
            }
            finally
            {
                DisConnect();
            }

            return count;
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="remotePath">远程路径("/test/abc.txt")</param>
        /// <returns></returns>
        public bool DeleteFile(string remotePath)
        {
            bool boolResult = false;

            try
            {
                if (Connect())
                {
                    if(IsFileExists(remotePath))
                        ftpClient.DeleteFile(remotePath);
                    boolResult = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error("DeleteFile->文件删除 异常:" + ex.ToString() + "|*|remotePath:" + remotePath);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        /// <summary>
        /// 检测远程目录路径
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public string CheckDirPath(string dirPath)
        {
            //远端路径校验
            if (string.IsNullOrEmpty(dirPath))
            {
                dirPath = "/";
            }
            if (!dirPath.StartsWith("/"))
            {
                dirPath = "/" + dirPath;
            }
            if (!dirPath.EndsWith("/"))
            {
                dirPath += "/";
            }
            return dirPath;
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="remoteDic">远端目录("/test")</param>
        /// <returns></returns>
        public bool DeleteDirectory(string remoteDic)
        {
            bool boolResult = false;
            try
            {
                ////远端路径校验
                //if (string.IsNullOrEmpty(remoteDic))
                //{
                //    remoteDic = "/";
                //}
                //if (!remoteDic.StartsWith("/"))
                //{
                //    remoteDic = "/" + remoteDic;
                //}
                //if (!remoteDic.EndsWith("/"))
                //{
                //    remoteDic += "/";
                //}

                remoteDic = CheckDirPath(remoteDic);

                if (Connect())
                {
                    ftpClient.DeleteDirectory(remoteDic);
                    boolResult = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error("DeleteDirectory->删除目录 异常:" + ex.ToString());
            }
            finally
            {
                DisConnect();
            }
            return boolResult;
        }

        #region 判断文件是否存在
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="remotePath">远程路径("/test/abc.txt")</param>
        /// <returns></returns>
        public bool IsFileExists(string remotePath)
        {
            bool boolResult = false;

            try
            {
                if (Connect())
                {
                    boolResult = ftpClient.FileExists(remotePath);
                }
            }
            catch (Exception ex)
            {
                logger.Error("IsFileExists->判断文件是否存在 异常:" + ex.ToString() + "|*|remotePath:" + remotePath);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        #region 判断目录是否存在
        /// <summary>
        /// 判断目录是否存在
        /// </summary>
        /// <param name="remotePath">远程路径("/test")</param>
        /// <returns></returns>
        public bool IsDirExists(string remotePath)
        {
            bool boolResult = false;

            try
            {
                if (Connect())
                {
                    boolResult = ftpClient.DirectoryExists(remotePath);
                }
            }
            catch (Exception ex)
            {
                logger.Error("IsDirExists->判断目录是否存在 异常:" + ex.ToString() + "|*|remotePath:" + remotePath);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        #region 新建目录
        /// <summary>
        /// 新建目录
        /// </summary>
        /// <param name="remoteDic">远程目录("/test")</param>
        /// <returns></returns>
        public bool MakeDir(string remoteDic)
        {
            bool boolResult = false;

            try
            {
                if (Connect())
                {
                    ftpClient.CreateDirectory(remoteDic);

                    boolResult = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error("MakeDir->新建目录 异常:" + ex.ToString() + "|*|remoteDic:" + remoteDic);
            }
            finally
            {
                DisConnect();
            }

            return boolResult;
        }
        #endregion

        #region 清理
        /// <summary>
        /// 清理
        /// </summary>
        public void Clean()
        {
            //断开FTP
            DisConnect();

            if (ftpClient != null)
            {
                ftpClient.Dispose();
            }
        }
        #endregion
    }
}

 

/// <summary>
    /// Ftp配置结构
    /// </summary>
    public class FtpConfig
    {
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public FtpConfig()
        {
            this.int_FtpReadWriteTimeout = 60000;
            this.bool_FtpUseBinary = true;
            this.bool_FtpUsePassive = true;
            this.bool_FtpKeepAlive = true;
            this.bool_FtpEnableSsl = false;
            this.int_RetryTimes = 3;
        }
        #endregion

        /// <summary>
        /// Ftp 标识
        /// </summary>
        public string str_Name { get; set; }
        /// <summary>
        /// FTP地址
        /// </summary>
        public string str_FtpUri { get; set; }
        /// <summary>
        /// FTP端口
        /// </summary>
        public int int_FtpPort { get; set; }


        private string _str_FtpPath = string.Empty;

        /// <summary>
        /// FTP路径(/test)
        /// </summary>
        public string str_FtpPath {
            get { return _str_FtpPath; }
            set { _str_FtpPath = CheckDirPath(value); }
        }
        /// <summary>
        /// FTP用户名
        /// </summary>
        public string str_FtpUserID { get; set; }
        /// <summary>
        /// FTP密码
        /// </summary>
        public string str_FtpPassword { get; set; }
        /// <summary>
        /// FTP密码是否被加密
        /// </summary>
        public bool bool_IsEncrypt { get; set; }
        /// <summary>
        /// 读取或写入超时之前的毫秒数。默认值为 30,000 毫秒。
        /// </summary>
        public int int_FtpReadWriteTimeout { get; set; }
        /// <summary>
        /// true,指示服务器要传输的是二进制数据;false,指示数据为文本。默认值为true。
        /// </summary>
        public bool bool_FtpUseBinary { get; set; }
        /// <summary>
        /// true,被动模式;false,主动模式(主动模式可能被防火墙拦截)。默认值为true。
        /// </summary>
        public bool bool_FtpUsePassive { get; set; }
        /// <summary>
        /// 是否保持连接。
        /// </summary>
        public bool bool_FtpKeepAlive { get; set; }
        /// <summary>
        /// 是否启用SSL。
        /// </summary>
        public bool bool_FtpEnableSsl { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        public string str_Describe { get; set; }
        /// <summary>
        /// 重试次数
        /// </summary>
        public int int_RetryTimes { get; set; }
        /// <summary>
        /// 版本号
        /// </summary>
        public string str_Ver { get; set; }


        /// <summary>
        /// 检测远程目录路径
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public string CheckDirPath(string dirPath)
        {
            //远端路径校验
            if (string.IsNullOrEmpty(dirPath))
            {
                dirPath = "/";
            }
            if (!dirPath.StartsWith("/"))
            {
                dirPath = "/" + dirPath;
            }
            if (!dirPath.EndsWith("/"))
            {
                dirPath += "/";
            }
            return dirPath;
        }
    }

 

posted @ 2021-03-30 14:09  jevan  阅读(308)  评论(0编辑  收藏  举报