C#FTPファイルのアップロードとダウンロードを実現

9253 ワード

投稿:https://www.cnblogs.com/anonymous-qsh/p/7858361.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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)
        {
        }

        /// 
        ///     
        /// 
        ///    
        ///    
        ///   
        ///       21
        ///        
        ///     ssl     
        ///      
        ///                       
        ///          5min
        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

        /// 
        ///   URL
        /// 
        ///    
        ///   
        ///    
        ///      URL
        private string UrlCombine(string host, string remotePath, string fileName)
        {
            string result = new Uri(new Uri(new Uri(host.TrimEnd('/')), remotePath), fileName).ToString(); ;
            return result;
        }

        /// 
        ///     
        /// 
        ///   
        ///   
        ///    request  
        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;
        }

        /// 
        ///     
        /// 
        ///     
        ///      
        ///        true
        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;
        }

        

        /// 
        ///     
        /// 
        ///        
        ///             
        ///        true
        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("172.17.204.59", "", "");
            //  
            //ftpHelper.Download("java.rar", "D:\\java1.rar");
            //  
            FileInfo fileInfo = new FileInfo("d:\\java1.rar");
            ftpHelper.Upload(fileInfo, "aaa.rar");
        }

    }
}

詳細FtpWebRequestドキュメントを表示するには、次の手順に従います.https://msdn.microsoft.com/zh-cn/library/system.net.ftpwebrequest.usepassive(v=vs.110).aspx