2018年6月27日 星期三

[C#] 存取FTP伺服器檔案目錄程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace My.Helper
{
    public class FTPHelper
    {
        //主機名稱
        public string HostName { get; set; }

        //連接埠
        public int Port { get; set; }

        //帳號
        public string UserID { get; set; }

        //密碼
        public string Password { get; set; }

        //FTP網址
        public string URL
        {
            get
            {
                return String.Format("ftp://{0}:{1}/", HostName, Port);
            }
        }

        //FTP完整網址
        public string FullURL
        {
            get
            {
                return String.Format("ftp://{0}:{1}@{2}:{3}/", UserID, Password, HostName, Port);
            }
        }

        /// 
        /// 建構子
        /// 
        public FTPHelper() : this("localhost", 21, "anonymous", "")
        {
        }

        /// 
        /// 建構子
        /// 
        /// 
        /// 
        /// 
        /// 
        public FTPHelper(string HostName, string UserID, string Password) : this(HostName, 21, UserID, Password)
        {
        }

        /// 
        /// 建構子
        /// 
        /// 
        /// 
        /// 
        /// 
        public FTPHelper(string HostName, int Port, string UserID, string Password)
        {
            this.HostName = HostName;
            this.Port = Port;
            this.UserID = UserID;
            this.Password = Password;
        }

        /// 
        /// 取得FtpWebRequest
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private FtpWebRequest GetFtpWebRequest(string url, string method, bool keepAlive, int timeout)
        {
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(url);
            request.Credentials = new NetworkCredential(UserID, Password);
            request.Method = method;
            request.KeepAlive = keepAlive;
            request.Timeout = timeout;
            return request;
        }

        /// 
        /// 將相對路徑轉為FTP的URI
        /// 
        /// 
        /// 
        private string PathToUri(string path)
        {
            //傳入絕對路徑,不變
            if (path.Substring(0, 6).ToLower().Equals("ftp://"))
            {
                return path;
            }

            //傳入空字串或根目錄符號,改成URL
            if (string.IsNullOrEmpty(path) || path.Equals(".") || path.Equals("/"))
            {
                return URL;
            }

            //傳入其他相對路徑,URL+path
            return URL + path;
        }

        /// 
        /// 測試登入FTP連線是否正常
        /// 
        /// 
        /// 
        public FTPResult Login()
        {
            FtpWebRequest request;
            try
            {
                request = GetFtpWebRequest(URL, WebRequestMethods.Ftp.ListDirectory, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "連線成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "連線失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
        }

        /// 
        /// 下載檔案
        /// 
        /// FTP檔案路徑
        /// 本機存檔路徑
        /// 
        public FTPResult DownloadFile(string downloadPath, string savePath)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(downloadPath);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.DownloadFile, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                Stream ftpStream = response.GetResponseStream();
                using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
                {
                    int bufferSize = 2048;
                    byte[] buffer = new byte[bufferSize];
                    int readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        fileStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                }
                ftpStream.Close();
                ftpStream.Dispose();

                var result = new FTPResult()
                {
                    result = true,
                    message = "下載成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "下載失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
        }

        /// 
        /// 上傳檔案
        /// 
        /// 上傳FTP檔案路徑
        /// 本機檔案路徑
        /// 
        public FTPResult UploadFile(string uploadPath, string filePath)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(uploadPath);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.UploadFile, true, 60000);

                Stream ftpStream = request.GetRequestStream();
                using (FileStream fileStream = File.OpenRead(filePath))
                {
                    int bufferSize = 2048;
                    byte[] buffer = new byte[bufferSize];
                    int readCount = fileStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        ftpStream.Write(buffer, 0, readCount);
                        readCount = fileStream.Read(buffer, 0, bufferSize);
                    }
                }
                ftpStream.Close();
                ftpStream.Dispose();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                var result = new FTPResult()
                {
                    result = true,
                    message = "上傳成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "上傳失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 刪除檔案
        /// 
        /// 
        /// 
        public FTPResult DeleteFile(string deleteFilePath)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(deleteFilePath);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.DeleteFile, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "刪除成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "刪除失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 取得檔案大小
        /// 
        /// 
        /// 
        public FTPResult GetFileSize(string filePath)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(filePath);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.GetFileSize, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "取得檔案大小成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "取得檔案大小失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 更改檔案或目錄名稱
        /// 
        /// 
        /// 
        /// 
        public FTPResult Rename(string oldName, string newName)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(oldName);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.Rename, true, 60000);
                request.RenameTo = newName;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "更名成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "更名失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 取得目錄清單
        /// 
        /// 
        /// 
        public FTPResult ListDirectory(string path, string type)
        {
            FtpWebRequest request;
            try
            {
                string URI;
                if (string.IsNullOrEmpty(path) || path.Equals(".") || path.Equals("/"))
                {
                    URI = URL;
                }
                else
                {
                    URI = PathToUri(path);
                }

                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.ListDirectory, true, -1);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                List directoryList = new List();
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string directory = reader.ReadLine();
                    while (directory != null)
                    {
                        if (directory.Contains(type))
                        {
                            directoryList.Add(directory);
                        }
                            directory = reader.ReadLine();
                        
                    }
                }

                var result = new FTPResult()
                {
                    result = true,
                    message = "取得目錄清單成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = directoryList,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "取得目錄清單失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 新增目錄
        /// 
        /// 
        /// 
        public FTPResult MakeDirectory(string dictionary)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(dictionary);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.MakeDirectory, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "新增目錄成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "新增目錄失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }

        /// 
        /// 移除目錄
        /// 
        /// 
        /// 
        public FTPResult RemoveDirectory(string dictionary)
        {
            FtpWebRequest request;
            try
            {
                string URI = PathToUri(dictionary);
                request = GetFtpWebRequest(URI, WebRequestMethods.Ftp.RemoveDirectory, true, 60000);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                var result = new FTPResult()
                {
                    result = true,
                    message = "移除目錄成功!",
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    contentLength = response.ContentLength,
                    directoryList = null,
                    exception = null
                };

                response.Close();
                response.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                return new FTPResult()
                {
                    result = false,
                    message = "移除目錄失敗!",
                    statusDescription = "",
                    contentLength = 0,
                    directoryList = null,
                    exception = ex
                };
            }
            finally
            {
                request = null;
            }
        }
    }
}

沒有留言:

張貼留言