当前位置:首页 > C#教程 > C#高级

C# 实现FTP上传和下载


c# 实现ftp下载文件

初学c# 需要用到ftp下载文件,在这里记录一下。

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.net;
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;

        #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);

                    using (stream rs = request.getrequeststream())
                    using (filestream fs = localfile.openread())
                    {
                        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;
                    }
                }
                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;
        }

    }
} 

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!