FTP的完整類<1><轉>

taogchan發表於2011-11-29
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Globalization;
using System.Text.RegularExpressions;
namespace System.Net.Ftp
{
    ///
    /// FTP處理操作類
    /// 功能:
    /// 下載檔案
    /// 上傳檔案
    /// 上傳檔案的進度資訊
    /// 下載檔案的進度資訊
    /// 刪除檔案
    /// 列出檔案
    /// 列出目錄
    /// 進入子目錄
    /// 退出當前目錄返回上一層目錄
    /// 判斷遠端檔案是否存在
    /// 判斷遠端檔案是否存在
    /// 刪除遠端檔案   
    /// 建立目錄
    /// 刪除目錄
    /// 檔案(目錄)改名
    ///
    ///
    /// 建立人:南瘋
    /// 建立時間:2007年4月28日
    ///

    #region 檔案資訊結構
    public struct FileStruct
    {
        public string Flags;
        public string Owner;
        public string Group;
        public bool IsDirectory;
        public DateTime CreateTime;
        public string Name;
    }
    public enum FileListStyle
    {
        UnixStyle,
        WindowsStyle,
        Unknown
    }
    #endregion
    public class clsFTP
    {
        #region 屬性資訊
        ///
        /// FTP請求物件
        ///

        FtpWebRequest Request = null;
        ///
        /// FTP響應物件
        ///

        FtpWebResponse Response = null;
        ///
        /// FTP伺服器地址
        ///

        private Uri _Uri;
        ///
        /// FTP伺服器地址
        ///

        public Uri Uri
        {
            get
            {
                if (_DirectoryPath == "/")
                {
                    return _Uri;
                }
                else
                {
                    string strUri = _Uri.ToString();
                    if (strUri.EndsWith("/"))
                    {
                        strUri = strUri.Substring(0, strUri.Length - 1);
                    }
                    return new Uri(strUri + this.DirectoryPath);
                }
            }
            set
            {
                if (value.Scheme != Uri.UriSchemeFtp)
                {
                    throw new Exception("Ftp 地址格式錯誤!");
                }
                _Uri = new Uri(value.GetLeftPart(UriPartial.Authority));
                _DirectoryPath = value.AbsolutePath;
                if (!_DirectoryPath.EndsWith("/"))
                {
                    _DirectoryPath += "/";
                }
            }
        }
        ///
        /// 當前工作目錄
        ///

        private string _DirectoryPath;
        ///
        /// 當前工作目錄
        ///

        public string DirectoryPath
        {
            get { return _DirectoryPath; }
            set { _DirectoryPath = value; }
        }
        ///
        /// FTP登入使用者
        ///

        private string _UserName;
        ///
        /// FTP登入使用者
        ///

        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; }
        }
        ///
        /// 錯誤資訊
        ///

        private string _ErrorMsg;
        ///
        /// 錯誤資訊
        ///

        public string ErrorMsg
        {
            get { return _ErrorMsg; }
            set { _ErrorMsg = value; }
        }
        ///
        /// FTP登入密碼
        ///

        private string _Password;
        ///
        /// FTP登入密碼
        ///

        public string Password
        {
            get { return _Password; }
            set { _Password = value; }
        }
        ///
        /// 連線FTP伺服器的代理服務
        ///

        private WebProxy _Proxy = null;
        ///
        /// 連線FTP伺服器的代理服務
        ///

        public WebProxy Proxy
        {
            get
            {
                return _Proxy;
            }
            set
            {
                _Proxy = value;
            }
        }
        ///
        /// 是否需要刪除臨時檔案
        ///

        private bool _isDeleteTempFile = false;
        ///
        /// 非同步上傳所臨時生成的檔案
        ///

        private string _UploadTempFile = "";
        #endregion
        #region 事件
        public delegate void De_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e);
        public delegate void De_DownloadDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
        public delegate void De_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e);
        public delegate void De_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e);
        ///
        /// 非同步下載進度發生改變觸發的事件
        ///

        public event De_DownloadProgressChanged DownloadProgressChanged;
        ///
        /// 非同步下載檔案完成之後觸發的事件
        ///

        public event De_DownloadDataCompleted DownloadDataCompleted;
        ///
        /// 非同步上傳進度發生改變觸發的事件
        ///

        public event De_UploadProgressChanged UploadProgressChanged;
        ///
        /// 非同步上傳檔案完成之後觸發的事件
        ///

        public event De_UploadFileCompleted UploadFileCompleted;
        #endregion
        #region 構造解構函式
        ///
        /// 建構函式
        ///

        /// FTP地址
        /// 登入使用者名稱
        /// 登入密碼
        public clsFTP(Uri FtpUri, string strUserName, string strPassword)
        {
            this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
            _DirectoryPath = FtpUri.AbsolutePath;
            if (!_DirectoryPath.EndsWith("/"))
            {
                _DirectoryPath += "/";
            }
            this._UserName = strUserName;
            this._Password = strPassword;
            this._Proxy = null;
        }
        ///
        /// 建構函式
        ///

        /// FTP地址
        /// 登入使用者名稱
        /// 登入密碼
        /// 連線代理
        public clsFTP(Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
        {
            this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
            _DirectoryPath = FtpUri.AbsolutePath;
            if (!_DirectoryPath.EndsWith("/"))
            {
                _DirectoryPath += "/";
            }
            this._UserName = strUserName;
            this._Password = strPassword;
            this._Proxy = objProxy;
        }
        ///
        /// 建構函式
        ///

        public clsFTP()
        {
            this._UserName = "anonymous";  //匿名使用者
            this._Password = "@anonymous";
            this._Uri = null;
            this._Proxy = null;
        }
        ///
        /// 解構函式
        ///

        ~clsFTP()
        {
            if (Response != null)
            {
                Response.Close();
                Response = null;
            }
            if (Request != null)
            {
                Request.Abort();
                Request = null;
            }
        }
        #endregion
        #region 建立連線
        ///
        /// 建立FTP連結,返回響應物件
        ///

        /// FTP地址
        /// 操作命令
        private FtpWebResponse Open(Uri uri, string FtpMathod)
        {
            try
            {
                Request = (FtpWebRequest)WebRequest.Create(uri);
                Request.Method = FtpMathod;
                Request.UseBinary = true;
                Request.Credentials = new NetworkCredential(this.UserName, this.Password);
                if (this.Proxy != null)
                {
                    Request.Proxy = this.Proxy;
                }
                return (FtpWebResponse)Request.GetResponse();
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        ///
        /// 建立FTP連結,返回請求物件
        ///

        /// FTP地址
        /// 操作命令
        private FtpWebRequest OpenRequest(Uri uri, string FtpMathod)
        {
            try
            {
                Request = (FtpWebRequest)WebRequest.Create(uri);
                Request.Method = FtpMathod;
                Request.UseBinary = true;
                Request.Credentials = new NetworkCredential(this.UserName, this.Password);
                if (this.Proxy != null)
                {
                    Request.Proxy = this.Proxy;
                }
                return Request;
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion
        #region 下載檔案
        ///
        /// 從FTP伺服器下載檔案,使用與遠端檔案同名的檔名來儲存檔案
        ///

        /// 遠端檔名
        /// 本地路徑
        public bool DownloadFile(string RemoteFileName, string LocalPath)
        {
            return DownloadFile(RemoteFileName, LocalPath, RemoteFileName);
        }
        ///
        /// 從FTP伺服器下載檔案,指定本地路徑和本地檔名
        ///

        /// 遠端檔名
        /// 本地路徑
        /// 儲存檔案的本地路徑,後面帶有"\"
        /// 儲存本地的檔名
        public bool DownloadFile(string RemoteFileName, string LocalPath, string LocalFileName)
        {
            byte[] bt = null;
            try
            {
                if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
                {
                    throw new Exception("非法檔名或目錄名!");
                }
                if (!Directory.Exists(LocalPath))
                {
                    throw new Exception("本地檔案路徑不存在!");
                }
                string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
                if (File.Exists(LocalFullPath))
                {
                    throw new Exception("當前路徑下已經存在同名檔案!");
                }
                bt = DownloadFile(RemoteFileName);
                if (bt != null)
                {
                    FileStream stream = new FileStream(LocalFullPath, FileMode.Create);
                    stream.Write(bt, 0, bt.Length);
                    stream.Flush();
                    stream.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        ///
        /// 從FTP伺服器下載檔案,返回檔案二進位制資料
        ///

        /// 遠端檔名
        public byte[] DownloadFile(string RemoteFileName)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName))
                {
                    throw new Exception("非法檔名或目錄名!");
                }
                Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile);
                Stream Reader = Response.GetResponseStream();
                MemoryStream mem = new MemoryStream(1024 * 500);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                int TotalByteRead = 0;
                while (true)
                {
                    bytesRead = Reader.Read(buffer, 0, buffer.Length);
                    TotalByteRead += bytesRead;
                    if (bytesRead == 0)
                        break;
                    mem.Write(buffer, 0, bytesRead);
                }
                if (mem.Length > 0)
                {
                    return mem.ToArray();
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-712366/,如需轉載,請註明出處,否則將追究法律責任。

相關文章