C# 实现FTP文件的上传和下载_被门夹过的核桃还能补脑么的博客-程序员信息网_c#代码实现android ftp上下传文件

技术标签: 前端  开发日记  

C# 实现FTP文件的上传和下载

任务

任务:在Visual Studio中用C#语言实现对ftp服务器上文件的上传和下载。
现状:初步了解c#语法,对库一无所知
解决:copy别人代码 https://www.cnblogs.com/anonymous-qsh/p/7858361.html 后续修改

代码


using System; //.net基础类型和通用类型
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
//重点是里面用来网络开发的WebRequest 和 WebResponse 类
using System.IO;
//对文件和目录操作
using System.Threading;

namespace FtpUtils
{
    
    class FtpHelper
    {
    
        // 默认常量定义
        private static readonly string rootPath = "/";
        private static readonly int defaultReadWriteTimeout = 300000;
        //读写时间
        private static readonly int defaultFtpPort = 21;
        //ftp默认端口号21

        #region 设置初始化参数
        //region用于将代码块折叠,方便查找
        private string host = string.Empty;
        
        public string Host
        {
    
            get
            {
    
                return this.host ?? string.Empty;
            }
            //访问器
        }

        private string username = string.Empty;
        
        public string Username
        {
    
            get
            {
    
                return this.username;
            }
        }

        private string password = string.Empty;
        
        public string Password
        {
    
            get
            {
    
                return this.password;
            }
        }

        IWebProxy proxy = null;
        
        public IWebProxy Proxy
        {
    
            get
            {
    
                return this.proxy;
            }
            set
            {
    
                this.proxy = value;
            }
        }

        private int port = defaultFtpPort;
        public int Port
        {
    
            get
            {
    
                return port;
            }
            set
            {
    
                this.port = value;
            }
        }

        private bool enableSsl = false;
        public bool EnableSsl
        {
    
            get
            {
    
                return enableSsl;
            }
        }

        private bool usePassive = true;
        public bool UsePassive
        {
    
            get
            {
    
                return usePassive;
            }
            set
            {
    
                this.usePassive = value;
            }
        }

        private bool useBinary = true;
        public bool UserBinary
        {
    
            get
            {
    
                return useBinary;
            }
            set
            {
    
                this.useBinary = value;
            }
        }

        private string remotePath = rootPath;
        public string RemotePath
        {
    
            get
            {
    
                return remotePath;
            }
            set
            {
    
                string result = rootPath;
                if (!string.IsNullOrEmpty(value) && value != rootPath)
                {
    
                    result = Path.Combine(Path.Combine(rootPath, value.TrimStart('/').TrimEnd('/')), "/"); // 进行路径的拼接
                }
                this.remotePath = result;
            }
        }

        private int readWriteTimeout = defaultReadWriteTimeout;
        public int ReadWriteTimeout
        {
    
            get
            {
    
                return readWriteTimeout;
            }
            set
            {
    
                this.readWriteTimeout = value;
            }
        }
        #endregion

        #region 构造函数

        public FtpHelper(string host, string username, string password)
            : this(host, username, password, defaultFtpPort, null, false, true, true, defaultReadWriteTimeout)
        {
    
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host">主机名</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="port">端口号 默认21</param>
        /// <param name="proxy">代理 默认没有</param>
        /// <param name="enableSsl">是否使用ssl 默认不用</param>
        /// <param name="useBinary">使用二进制</param>
        /// <param name="usePassive">获取或设置客户端应用程序的数据传输过程的行为</param>
        /// <param name="readWriteTimeout">读写超时时间 默认5min</param>
        public FtpHelper(string host, string username, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive, int readWriteTimeout)
        {
    
            this.host = host.ToLower().StartsWith("ftp://") ? host : "ftp://" + host;
            this.username = username;
            this.password = password;
            this.port = port;
            this.proxy = proxy;
            this.enableSsl = enableSsl;
            this.useBinary = useBinary;
            this.usePassive = usePassive;
            this.readWriteTimeout = readWriteTimeout;
        }
        #endregion

        /// <summary>
        /// 拼接URL
        /// </summary>
        /// <param name="host">主机名</param>
        /// <param name="remotePath">地址</param>
        /// <param name="fileName">文件名</param>
        /// <returns>返回完整的URL</returns>
        private string UrlCombine(string host, string remotePath, string fileName)
        {
    
            string result = new Uri(new Uri(new Uri(host.TrimEnd('/')), remotePath), fileName).ToString(); ;
            return result;
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">方法</param>
        /// <returns>返回 request对象</returns>
        private FtpWebRequest CreateConnection(string url, string method)
        {
    
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
            request.Credentials = new NetworkCredential(this.username, this.password);
            request.Proxy = this.proxy;
            request.KeepAlive = false;
            request.UseBinary = useBinary;
            request.UsePassive = usePassive;
            request.EnableSsl = enableSsl;
            request.Method = method;
            Console.WriteLine(request);
            return request;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="localFile">本地文件</param>
        /// <param name="remoteFileName">上传文件名</param>
        /// <returns>上传成功返回 true</returns>
        public bool Upload(FileInfo localFile, string remoteFileName)
        {
    
            bool result = false;
            if (localFile.Exists)
            {
    
                try
                {
    
                    string url = UrlCombine(Host, RemotePath, remoteFileName);  //统一资源定位符
                    FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.UploadFile);//用FtpWebRequest创建连接

                    using (Stream rs = request.GetRequestStream())
                    using (FileStream fs = localFile.OpenRead())
                    //using用于在代码块执行结束后释放资源
                    {
    
                        byte[] buffer = new byte[1024 * 4];
                        int count = fs.Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
    
                            rs.Write(buffer, 0, count);
                            count = fs.Read(buffer, 0, buffer.Length);
                        }
                        fs.Close();
                        result = true;
                        //filestream -> stream
                    }
                }
                catch (WebException ex)
                {
    
                    // MessageBox.Show(ex.Message);
                }
                return result;
            }
            // 处理本地文件不存在的情况
            return false;
        }



        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="serverName">服务器文件名称</param>
        /// <param name="localName">需要保存在本地的文件名称</param>
        /// <returns>下载成功返回 true</returns>
        public bool Download(string serverName, string localName)
        {
    
            bool result = false;
            using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate))
            {
    
                try
                {
    
                    string url = UrlCombine(Host, RemotePath, serverName);
                    Console.WriteLine(url);

                    FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.DownloadFile);
                    request.ContentOffset = fs.Length;
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    {
    
                        fs.Position = fs.Length;
                        byte[] buffer = new byte[1024 * 4];
                        int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
    
                            fs.Write(buffer, 0, count);
                            count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                        }
                        response.GetResponseStream().Close();
                    }
                    result = true;
                }
                catch (WebException ex)
                {
    
                    // 处理ftp连接中的异常
                }
            }
            return result;
        }

        //main函数
        static void Main(string[] args)
        {
    
            FtpHelper ftpHelper = new FtpHelper("192.168.199.86", "ftpcp13","cpcp1010");
            //下载
            ftpHelper.Download("dingshengli.txt", "D:\\dingshengli2.txt");
            //上传
            //FileInfo fileInfo = new FileInfo("d:\\dingshengli.txt");
            //ftpHelper.Upload(fileInfo, "dingshengli.txt");
        }

    }
}

功能完善

以上代码不支持在服务器上创建路径和查找、删除文件,现在对此进行改进。
参考代码:https://www.cnblogs.com/stry/p/9875439.html
WebRequest.ftp类的相关文档 https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webrequestmethods.ftp?view=netcore-3.1

CreateRequest有以下几种方式:

AppendFile
表示要用于将文件追加到 FTP 服务器上的现有文件的 FTP APPE 协议方法。
DeleteFile
表示要用于删除 FTP 服务器上的文件的 FTP DELE 协议方法。
DownloadFile
表示要用于从 FTP 服务器下载文件的 FTP RETR 协议方法。
GetDateTimestamp
表示要用于从 FTP 服务器上的文件检索日期时间戳的 FTP MDTM 协议方法。
GetFileSize
表示要用于检索 FTP 服务器上的文件大小的 FTP SIZE 协议方法。
ListDirectory
表示获取 FTP 服务器上的文件的简短列表的 FTP NLIST 协议方法。
ListDirectoryDetails
表示获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法。
MakeDirectory
表示在 FTP 服务器上创建目录的 FTP MKD 协议方法。
PrintWorkingDirectory
表示打印当前工作目录的名称的 FTP PWD 协议方法。
RemoveDirectory
表示移除目录的 FTP RMD 协议方法。
Rename
表示重命名目录的 FTP RENAME 协议方法。
UploadFile
表示将文件上载到 FTP 服务器的 FTP STOR 协议方法。
UploadFileWithUniqueName
表示将具有唯一名称的文件上载到 FTP 服务器的 FTP STOU 协议方法。

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;

namespace FtpFileProcess
{
    
    [Serializable]
    public class DeviceFile
    {
    
        public string FileName;
        //{
    
        //    get
        //    {
    
        //        return this.FileNmae;
        //    }
        //    set
        //    {
    
        //        this.FileNmae = value;
        //    }
        //}

        public string DevNmae
        {
    
            get;
            set;
        
        }

        public string RemotePath
        {
    
            get;
            set;
            
        }

        public string LocalPath
        {
    
            get;
            set;
        }

        public long Size
        {
    
            get;
            set;
        }
       

        public DateTime SaveTime
        {
    
            get;
            set;
            
        }
    }

    public class FtpClient
    {
    
        #region 构造函数
        /// <summary>
        /// 创建FTP工具
        /// <para>
        /// 默认不使用SSL,使用二进制传输方式,使用被动模式
        /// </para>
        /// </summary>
        /// <param name="host">主机名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="password">密码</param>
        public FtpClient(string host, string userId, string password)
            : this(host, userId, password, 21, null, false, true, true)
        {
    
        }
        /// <summary>
        /// 创建FTP工具
        /// </summary>
        /// <param name="host">主机名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="port">端口</param>
        /// <param name="enableSsl">允许Ssl</param>
        /// <param name="proxy">代理</param>
        /// <param name="useBinary">允许二进制</param>
        /// <param name="usePassive">允许被动模式</param>
        public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive)
        {
    
            this.userId = userId;
            this.password = password;
            if (host.ToLower().StartsWith("ftp://"))
            {
    
                this.host = host;
            }
            else
            {
    
                this.host = "ftp://" + host;
            }
            this.port = port;
            this.proxy = proxy;
            this.enableSsl = enableSsl;
            this.useBinary = useBinary;
            this.usePassive = usePassive;
        }
        #endregion
        #region 主机
        private string host = string.Empty;
        /// <summary>
        /// 主机
        /// </summary>
        public string Host
        {
    
            get
            {
    
                return this.host ?? string.Empty;
            }
        }
        #endregion
        #region 登录用户名
        private string userId = string.Empty;
        /// <summary>
        /// 登录用户名
        /// </summary>
        public string UserId
        {
    
            get
            {
    
                return this.userId;
            }
        }
        #endregion
        #region 密码
        private string password = string.Empty;
        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
    
            get
            {
    
                return this.password;
            }
        }
        #endregion
        #region 代理
        IWebProxy proxy = null;
        /// <summary>
        /// 代理
        /// </summary>
        public IWebProxy Proxy
        {
    
            get
            {
    
                return this.proxy;
            }
            set
            {
    
                this.proxy = value;
            }
        }
        #endregion
        #region 端口
        private int port = 21;
        /// <summary>
        /// 端口
        /// </summary>
        public int Port
        {
    
            get
            {
    
                return port;
            }
            set
            {
    
                this.port = value;
            }
        }
        #endregion
        #region 设置是否允许Ssl
        private bool enableSsl = false;
        /// <summary>
        /// EnableSsl
        /// </summary>
        public bool EnableSsl
        {
    
            get
            {
    
                return enableSsl;
            }
        }
        #endregion
        #region 使用被动模式
        private bool usePassive = true;
        /// <summary>
        /// 被动模式
        /// </summary>
        public bool UsePassive
        {
    
            get
            {
    
                return usePassive;
            }
            set
            {
    
                this.usePassive = value;
            }
        }
        #endregion
        #region 二进制方式
        private bool useBinary = true;
        /// <summary>
        /// 二进制方式
        /// </summary>
        public bool UseBinary
        {
    
            get
            {
    
                return useBinary;
            }
            set
            {
    
                this.useBinary = value;
            }
        }
        #endregion
        #region 远端路径
        private string remotePath = "/";
        /// <summary>
        /// 远端路径
        /// <para>
        ///     返回FTP服务器上的当前路径(可以是 / 或 /a/../ 的形式)
        /// </para>
        /// </summary>
        public string RemotePath
        {
    
            get
            {
    
                return remotePath;
            }
            set
            {
    
                string result = "/";
                if (!string.IsNullOrEmpty(value) && value != "/")
                {
    
                    result = "/" + value.TrimStart('/').TrimEnd('/') + "/";
                }
                this.remotePath = result;
            }
        }
        #endregion
        #region 创建一个FTP连接
        /// <summary>
        /// 创建一个FTP请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="method">请求方法</param>
        /// 
        /// <returns>FTP请求</returns>
        private FtpWebRequest CreateRequest(string url, string method)
        {
    
            //建立连接
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Credentials = new NetworkCredential(this.userId, this.password);
            request.Proxy = this.proxy;
            request.KeepAlive = false;//命令执行完毕之后关闭连接
            request.UseBinary = useBinary;
            request.UsePassive = usePassive;
            request.EnableSsl = enableSsl;
            request.Method = method;
            return request;
        }
        #endregion
        #region 上传一个文件到远端路径下
        /// <summary>
        /// 把文件上传到FTP服务器的RemotePath下
        /// </summary>
        /// <param name="localFile">本地文件信息</param>
        /// <param name="remoteFileName">要保存到FTP文件服务器上的名称</param>
        public bool Upload(FileInfo localFile, string remoteFileName)
        {
    
            bool result = false;
            if (localFile.Exists)
            {
    
                string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);
                //上传数据
                using (Stream rs = request.GetRequestStream())
                using (FileStream fs = localFile.OpenRead())
                {
    
                    byte[] buffer = new byte[4096];//4K
                    int count = fs.Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
    
                        rs.Write(buffer, 0, count);
                        count = fs.Read(buffer, 0, buffer.Length);
                    }
                    fs.Close();
                    result = true;
                }
                return result;
            }
            throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
        }
        #endregion
        #region 从FTP服务器上下载文件
        /// <summary>
        /// 从当前目录下下载文件
        /// <para>
        /// 如果本地文件存在,则从本地文件结束的位置开始下载.
        /// </para>
        /// </summary>
        /// <param name="serverName">服务器上的文件名称</param>
        /// <param name="localName">本地文件名称</param>
        /// <returns>返回一个值,指示是否下载成功</returns>
        public bool Download(string serverName, string localName)
        {
    
            bool result = false;
            using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate)) //创建或打开本地文件
            {
    
                //建立连接
                string url = Host.TrimEnd('/') + RemotePath + serverName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile);
                request.ContentOffset = fs.Length;
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
    
                    fs.Position = fs.Length;
                    byte[] buffer = new byte[4096];//4K
                    int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
    
                        fs.Write(buffer, 0, count);
                        count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                    }
                    response.GetResponseStream().Close();
                }
                result = true;
            }
            return result;
        }
        #endregion
        #region 重命名FTP服务器上的文件
        /// <summary>
        /// 文件更名
        /// </summary>
        /// <param name="oldFileName">原文件名</param>
        /// <param name="newFileName">新文件名</param>
        /// <returns>返回一个值,指示更名是否成功</returns>
        public bool Rename(string oldFileName, string newFileName)
        {
    
            bool result = false;
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath + oldFileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename);
            request.RenameTo = newFileName;
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                result = true;
            }
            return result;
        }
        #endregion

        #region
        public DateTime GetFileModifyDateTime(string fileName)
        {
    
            string url = Host.TrimEnd('/') + RemotePath + fileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetDateTimestamp);
            DateTime dt; 
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                dt = response.LastModified;
            }
            return dt;
        }
        #endregion

        #region 从当前目录下获取文件列表
        /// <summary>
        /// 获取当前目录下文件列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetFileList()
        {
    
            
             List<string> result = new List<string>();
            //建立连接
            
                string url = Host.TrimEnd('/') + RemotePath;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory);
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
    
                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
                    string line = reader.ReadLine();
                    while (line != null)
                    {
    
                        result.Add(line);
                        line = reader.ReadLine();
                    }
                }
            
            return result;
        }
        #endregion
        #region 从FTP服务器上获取文件和文件夹列表
        /// <summary>
        /// 获取详细列表 从FTP服务器上获取文件和文件夹列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetFileDetails()
        {
    
            List<string> result = new List<string>();
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {
    
                    result.Add(line);
                    line = reader.ReadLine();
                }
            }
            return result;
        }
        #endregion
        #region 从FTP服务器上删除文件
        /// <summary>
        /// 删除FTP服务器上的文件
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>返回一个值,指示是否删除成功</returns>
        public bool DeleteFile(string fileName)
        {
    
            bool result = false;
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath + fileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                result = true;
            }
            return result;
        }
        #endregion
        #region 在FTP服务器上创建目录
        /// <summary>
        /// 在当前目录下创建文件夹
        /// </summary>
        /// <param name="dirName">文件夹名称</param>
        /// <returns>返回一个值,指示是否创建成功</returns>
        public bool MakeDirectory(string dirName)
        {
    
            bool result = false;
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath + dirName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                result = true;
            }
            return result;
        }
        #endregion
        #region 从FTP服务器上删除目录
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="dirName">文件夹名称</param>
        /// <returns>返回一个值,指示是否删除成功</returns>
        public bool DeleteDirectory(string dirName)
        {
    
            bool result = false;
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath + dirName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                result = true;
            }
            return result;
        }
        #endregion
        #region 从FTP服务器上获取文件大小
        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public long GetFileSize(string fileName)
        {
    
            long result = 0;
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath + fileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
    
                result = response.ContentLength;
            }
            return result;
        }
        #endregion
        #region 给FTP服务器上的文件追加内容
        /// <summary>
        /// 给FTP服务器上的文件追加内容
        /// </summary>
        /// <param name="localFile">本地文件</param>
        /// <param name="remoteFileName">FTP服务器上的文件</param>
        /// <returns>返回一个值,指示是否追加成功</returns>
        public bool Append(FileInfo localFile, string remoteFileName)
        {
    
            if (localFile.Exists)
            {
    
                using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open))
                {
    
                    return Append(fs, remoteFileName);
                }
            }
            throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
        }
        /// <summary>
        /// 给FTP服务器上的文件追加内容
        /// </summary>
        /// <param name="stream">数据流(可通过设置偏移来实现从特定位置开始上传)</param>
        /// <param name="remoteFileName">FTP服务器上的文件</param>
        /// <returns>返回一个值,指示是否追加成功</returns>
        public bool Append(Stream stream, string remoteFileName)
        {
    
            bool result = false;
            if (stream != null && stream.CanRead)
            {
    
                //建立连接
                string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile);
                using (Stream rs = request.GetRequestStream())
                {
    
                    //上传数据
                    byte[] buffer = new byte[4096];//4K
                    int count = stream.Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
    
                        rs.Write(buffer, 0, count);
                        count = stream.Read(buffer, 0, buffer.Length);
                    }
                    result = true;
                }
            }
            return result;
        }
        #endregion
        #region 获取FTP服务器上的当前路径
        /// <summary>
        /// 获取FTP服务器上的当前路径
        /// </summary>
        public string CurrentDirectory
        {
    
            get
            {
    
                string result = string.Empty;
                string url = Host.TrimEnd('/') + RemotePath;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory);
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
    
                    string temp = response.StatusDescription;
                    int start = temp.IndexOf('"') + 1;
                    int end = temp.LastIndexOf('"');
                    if (end >= start)
                    {
    
                        result = temp.Substring(start, end - start);
                    }
                }
                return result;
            }
        }
        #endregion
        #region 检查当前路径上是否存在某个文件
        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="fileName">要检查的文件名</param>
        /// <returns>返回一个值,指示要检查的文件是否存在</returns>
        public bool CheckFileExist(string fileName)
        {
    
            bool result = false;
            if (fileName != null && fileName.Trim().Length > 0)
            {
    
                fileName = fileName.Trim();
                List<string> files = GetFileList();
                if (files != null && files.Count > 0)
                {
    
                    foreach (string file in files)
                    {
    
                        if (file.ToLower() == fileName.ToLower())
                        {
    
                            result = true;
                            break;
                        }
                    }
                }
            }
            return result;
        }
        #endregion

        #region

        #endregion


        #region
       
        //
        public List<DeviceFile> GetDeviceFile(string DevName, DateTime StartTime, DateTime EndTime)
        {
    

            //获取所有中间日期
            List<String> DateList = new List<String>();
            for (DateTime TmpTime = StartTime;  TmpTime<= EndTime; TmpTime = TmpTime.AddDays(1))
            {
    
                DateList.Add(TmpTime.ToString("yyyy/MM/dd"));
            }

            List<DeviceFile> result = new List<DeviceFile>();

            
            foreach (string tmpstr in DateList)
            {
    
                try
                {
    
                    RemotePath = DevName + "/" + tmpstr + "/";
                    List<string> filelist = new List<string>();
                    filelist = GetFileList();
                    foreach (string s in filelist)
                    {
    
                        Console.WriteLine(s);
                        long size = GetFileSize(s);
                        DateTime dt = GetFileModifyDateTime(s);

                        DeviceFile dev = new DeviceFile();
                        dev.FileName = s;
                        dev.DevNmae = DevName;
                        dev.RemotePath = RemotePath;
                        dev.Size = size;
                        dev.SaveTime = dt;

                        result.Add(dev);

                    }

                }
                catch(WebException ex)
                {
    
                    Console.WriteLine(ex.ToString());
                }
            }

            return result;
        }
        

        //下载文件
        public Boolean DownLoadDeviceFile(List<DeviceFile>  devfilelist,String localpath)
        {
    
            foreach(DeviceFile devfile in devfilelist)
            {
    
                RemotePath = devfile.RemotePath;
                if(Download(devfile.FileName, localpath+devfile.FileName))
                {
    
                    Console.WriteLine("DownLoad Successful:  "+ devfile.FileName);
               
                }
                else
                {
    
                    Console.WriteLine("DownLoad Failure:  "+devfile.FileName);
                    return false;
                }
            }

            return true;
        }

        //
//
#endregion


static void Main(string[] args)
        {
    
            FtpClient ftpHelper = new FtpClient("ip地址", "账户名", "密码");
            List<DeviceFile> devfilelist = new List<DeviceFile>();
            DateTime StartTime = new DateTime(2020, 9, 25);
            DateTime EndTime = new DateTime(2020, 9 ,29);
           
            devfilelist = ftpHelper.GetDeviceFile("设备名", StartTime, EndTime);

            ftpHelper.DownLoadDeviceFile(devfilelist, "本地路径" +"文件按名");

         }

    }
}

说明

设计了一个Device类用来存储文件属性,函数GetDeviceFile用来获得一个时间段内的文件,DownLoadDeviceFile用来根据Device列表下载相应的文件。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/DanielDingshengli/article/details/108778367

智能推荐

ijkplayer支持分段播放设置_jeffasd的博客-程序员信息网_android ijkvideo分段播放

http://blog.csdn.net/liushihua147/article/details/60962967?locationNum=10&fps=1http://blog.csdn.net/lhy412484577/article/details/68063917https://ffmpeg.org/ffmpeg-formats.html#concat-1

2019 VUE 常问面试题_小块布丁的博客-程序员信息网

VueVue的双向数据绑定原理是什么?答:vue.js 是采用数据劫持结合发布者-订阅者模式的方式,通过Object.defineProperty()来劫持各个属性的setter,getter,在数据变动时发布消息给订阅者,触发相应的监听回调。具体步骤:第一步:需要observe的数据对象进行递归遍历,包括子属性对象的属性,都加上 setter和getter这样的话,给这个对象的某个值...

javaweb下载excel文件_GeziGuo的博客-程序员信息网

方案一:使用servlet下载文件,代码写在servlet类中。maven依赖&lt;!-- java excel api --&gt;&lt;dependency&gt; &lt;groupId&gt;net.sourceforge.jexcelapi&lt;/groupId&gt; &lt;artifactId&gt;jxl&lt;/artifactId&gt; &lt...

python实现农历和阳历日期转换_feiyang5260的博客-程序员信息网_python 获取当前日期 农历

需安装sxtwl包,命令如下pip install sxtwl农历(Lunar calendar)&lt;-&gt;阳历(solar calendar)转换代码如下(基于python3):import sxtwl#日历中文索引ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u...

Activiti 流程启动及节点流转源码分析_衣舞晨风的博客-程序员信息网_节点流转

作者:jiankunking 出处:http://blog.csdn.net/jiankunking本文主要是以activiti-study中的xiaomage.xml流程图为例进行跟踪分析 具体的流程图如下: 流程图对应的XML文件如下:<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://www.omg.or

Redisson官方文档 - 4. 数据序列化_weixin_33756418的博客-程序员信息网

Redisson的对象编码类是用于将对象进行序列化和反序列化,以实现对该对象在Redis里的读取和存储。Redisson提供了以下几种的对象编码以供大家选择:编码类名称说明org.redisson.codec.JsonJacksonCodecJackson JSON 编码 默认编码org.redisson.codec.AvroJ...

随便推点

matlab求素数个数及素数的总和,算法(1---1000))_zzl8888888的博客-程序员信息网_matlab 求素数之和

clear%清空变量sum=5;%从第一个合数开始ss=0;%标记prime=[2 3];%初始数组,前两个素数for i=4:100for j=2:fix(sqrt(i))%求素数if mod(i,j)0ss=0;%不是素数为0break;%跳出for(j)的循环elsess=1;%是素数endendif ss1prime=[prime,i];%输出所有的值sum...

VHDL学习札记:library and Package_weixin_30482383的博客-程序员信息网

开发环境:VHDL, Leon3, Quartus应用场合:在VHDL设计文件中,常见到如下代码出现在首段,作为类似头文件的作用(例如Verilog中的include),本文阐述的是这段语句如何在工程中使用: 1 library ieee; 2 use ieee.std_logic_1164.all; 3 4 --Leon库 5 library grlib; 6 ...

System.InvalidOperationException: Connection must be valid and open_hungzz的博客-程序员信息网_system.invalidoperationexception: connection must

由于MySQL服务在长时间不连接之后断开了,断开之后的首次请求会抛出"System.InvalidOperationException: Connection must be valid and open."这个异常。那么既然是连接超时的问题,就要去MySQL中探究一下连接时间是怎么控制的。打开MySQL的控制台,运行:show variables like '%timeout%',查看和连接

java 反射机制之 getDeclaredMethod()获取方法,然后invoke执行实例对应的方法_开着奥迪卖小猪的博客-程序员信息网

关于反射中getDeclaredMethod().invoke()的学习,来源于项目中的一行代码:SubjectService.class.getDeclaredMethod(autoMatchConfig.getMethodName(), Integer.class).invoke(subjectService, GlobalConfig.OPEN_TO_IPLAN);获取反射的方法有...

mybatis踩过的坑_boyandddd的博客-程序员信息网_.test.cyclic.buffer.size=1048576

D:\opensources\jdk1.8.0_221\bin\java -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\IntelliJ IDEA 2017.3.5\lib\idea_rt.jar=62820:D:\IntelliJ IDEA 2017.3.5\bin" -Dfile.encoding=UTF-8 -classpath "D:\IntelliJ IDEA 2017.3.5\lib\idea_rt.jar;D:\Intell

rtmp 发送h264包,主要是sps,pps,i帧和非i帧_ybn187的博客-程序员信息网

28181流媒体,ps流解析,nalu分析,出来的数据封装成rtmp包发送rtmp,此处仅关心rtmp发送问题这个连接有完整的调用librtmp发送h264的代码,但是里面发送h264包时候有问题,没有区分包类型https://blog.csdn.net/godspeed513/article/details/8972947sps,pps包的构建可以参考这个连接https://blo...

推荐文章

热门文章

相关标签