C#操作FTP

 

代碼
不要忘記引入命名空間
using System.Net;
using System.IO;
下面的幾個步驟包括了使用FtpWebRequest類實現ftp功能的一般過程
1、創建一個FtpWebRequest對象,指向ftp服務器的uri
2、設置ftp的執行方法(上傳,下載等)
3、給FtpWebRequest對象設置屬性(是否支持ssl,是否使用二進制傳輸等)
4、設置登錄驗證(用戶名,密碼)
5、執行請求
6、接收相應流(如果需要的話)
7、如果沒有打開的流,則關閉ftp請求
開發任何ftp應用程序都需要一個相關的ftp服務器及它的配置信息。FtpWebRequest暴露了一些屬性來設置這些信息。
接下來的代碼示例了上傳功能
首先設置一個uri地址,包括路徑和文件名。這個uri被使用在FtpWebRequest實例中。
然後根據ftp請求設置FtpWebRequest對象的屬性
其中一些重要的屬性如下:
    Credentials - 指定登錄ftp服務器的用戶名和密碼。
    KeepAlive - 指定連接是應該關閉還是在請求完成之後關閉,默認爲true
    UseBinary - 指定文件傳輸的類型。有兩種文件傳輸模式,一種是Binary,另一種是ASCII。兩種方法在傳輸時,字節的第8位是不同的。ASCII使用第8位作爲錯誤控制,而Binary的8位都是有意義的。所以當你使用ASCII傳輸時要小心一些。簡單的說,如果能用記事本讀和寫的文件用ASCII傳輸就是安全的,而其他的則必須使用Binary模式。當然使用Binary模式發送ASCII文件也是非常好的。

    UsePassive - 指定使用主動模式還是被動模式。早先所有客戶端都使用主動模式,而且工作的很好,而現在因爲客戶端防火牆的存在,將會關閉一些端口,這樣主動模式將會失敗。在這種情況下就要使用被動模式,但是一些端口也可能被服務器的防火牆封掉。不過因爲ftp服務器需要它的ftp服務連接到一定數量的客戶端,所以他們總是支持被動模式的。這就是我們爲什麼要使用被動模式的原意,爲了確保數據可以正確的傳輸,使用被動模式要明顯優於主動模式。(譯者注:主動(PORT)模式建立數據傳輸通道是由服務器端發起的,服務器使用20端口連接客戶端的某一個大於1024的端口;在被動(PASV)模式中,數據傳輸的通道的建立是由FTP客戶端發起的,他使用一個大於1024的端口連接服務器的1024以上的某一個端口)
    ContentLength - 設置這個屬性對於ftp服務器是有用的,但是客戶端不使用它,因爲FtpWebRequest忽略這個屬性,所以在這種情況下,該屬性是無效的。但是如果我們設置了這個屬性,ftp服務器將會提前預知文件的大小(在upload時會有這種情況)
    Method - 指定當前請求是什麼命令(upload,download,filelist等)。這個值定義在結構體WebRequestMethods.Ftp中。
private void Upload(string filename)
{
   FileInfo fileInf = new FileInfo(filename);
   string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
   FtpWebRequest reqFTP;
   // 根據uri創建FtpWebRequest對象
   reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
   // ftp用戶名和密碼
   reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
   // 默認爲true,連接不會被關閉
   // 在一個命令之後被執行
   reqFTP.KeepAlive = false;
   // 指定執行什麼命令
   reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
   // 指定數據傳輸類型
   reqFTP.UseBinary = true;
   // 上傳文件時通知服務器文件的大小
   reqFTP.ContentLength = fileInf.Length;
   // 緩衝大小設置爲2kb
   int buffLength = 2048;
   byte[] buff = new byte[buffLength];
   int contentLen;
   // 打開一個文件流 (System.IO.FileStream) 去讀上傳的文件
   FileStream fs = fileInf.OpenRead();
   try
   {
       // 把上傳的文件寫入流
       Stream strm = reqFTP.GetRequestStream();
       // 每次讀文件流的2kb
       contentLen = fs.Read(buff, 0, buffLength);
       // 流內容沒有結束
       while (contentLen != 0)
       {
           // 把內容從file stream 寫入 upload stream
           strm.Write(buff, 0, contentLen);
           contentLen = fs.Read(buff, 0, buffLength);
       }
       // 關閉兩個流
       strm.Close();
       fs.Close();
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message, "Upload Error");
   }
}
以上代碼簡單的示例了ftp的上傳功能。創建一個指向某ftp服務器的FtpWebRequest對象,然後設置其不同的屬性Credentials,KeepAlive,Method,UseBinary,ContentLength。
打開本地機器上的文件,把其內容寫入ftp請求流。緩衝的大小爲2kb,無論上傳大文件還是小文件,這都是一個合適的大小。
private void Download(string filePath, string fileName)
{
   FtpWebRequest reqFTP;
   try
   {
       FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
       reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
       reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
       reqFTP.UseBinary = true;
       reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
       FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
       Stream ftpStream = response.GetResponseStream();
       long cl = response.ContentLength;
       int bufferSize = 2048;
       int readCount;
       byte[] buffer = new byte[bufferSize];
       readCount = ftpStream.Read(buffer, 0, bufferSize);
       while (readCount > 0)
       {
           outputStream.Write(buffer, 0, readCount);
           readCount = ftpStream.Read(buffer, 0, bufferSize);
       }
       ftpStream.Close();
       outputStream.Close();
       response.Close();
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
   }
}
上面的代碼實現了從ftp服務器上下載文件的功能。這不同於之前所提到的上傳功能,下載需要一個響應流,它包含着下載文件的內容。這個下載的文件是在FtpWebRequest對象中的uri指定的。在得到所請求的文件後,通過FtpWebRequest對象的GetResponse()方法下載文件。它將把文件作爲一個流下載到你的客戶端的機器上。
注意:我們可以設置文件在我們本地機器上的存放路徑和名稱。
public string[] GetFileList()
{   
   string[] downloadFiles;   
   StringBuilder result = new StringBuilder();   
   FtpWebRequest reqFTP;   
   try   
   {       
       reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));       
       reqFTP.UseBinary = true;       
       reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);       
       reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;       
       WebResponse response = reqFTP.GetResponse();       
       StreamReader reader = new StreamReader(response.GetResponseStream());       
       string line = reader.ReadLine();       
       while (line != null)       
       {           
           result.Append(line);           
           result.Append("\n");           
           line = reader.ReadLine();       
       }       
       // to remove the trailing '\n'       
       result.Remove(result.ToString().LastIndexOf('\n'), 1);       
       reader.Close();       
       response.Close();       
       return result.ToString().Split('\n');   
   }   
   catch (Exception ex)   
   {       
       System.Windows.Forms.MessageBox.Show(ex.Message);       
       downloadFiles = null;       
       return downloadFiles;   
   }
}
上面的代碼示例瞭如何從ftp服務器上獲得文件列表。uri指向ftp服務器的地址。我們使用StreamReader對象來存儲一個流,文件名稱列表通過“\r\n”分隔開,也就是說每一個文件名稱都佔一行。你可以使用StreamReader對象的ReadToEnd()方法來得到文件列表。上面的代碼中我們用一個StringBuilder對象來保存文件名稱,然後把結果通過分隔符分開後作爲一個數組返回。我確定只是一個比較好的方法。
其他的實現如Rename,Delete,GetFileSize,FileListDetails,MakeDir等與上面的幾段代碼類似,就不多說了。
注意:實現重命名的功能時,要把新的名字設置給FtpWebRequest對象的RenameTo屬性。連接指定目錄的時候,需要在FtpWebRequest對象所使用的uri中指明。

需要注意的地方
你在編碼時需要注意以下幾點:
    除非EnableSsl屬性被設置成true,否作所有數據,包括你的用戶名和密碼都將明文發給服務器,任何監視網絡的人都可以獲取到你連接服務器的驗證信息。如果你連接的ftp服務器提供了SSL,你就應當把EnableSsl屬性設置爲true。
    如果你沒有訪問ftp服務器的權限,將會拋出SecurityException錯誤
    發送請求到ftp服務器需要調用GetResponse方法。當請求的操作完成後,一個FtpWebResponse對象將返回。這個FtpWebResponse對象提供了操作的狀態和已經從ftp服務器上下載的數據。FtpWebResponse對象的StatusCode屬性提供了ftp服務器返回的最後的狀態代碼。FtpWebResponse對象的StatusDescription屬性爲這個狀態代碼的描述。

 

以下是寫好的一個類

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using System.Text.RegularExpressions;

namespace DSS.BLL
{
    public class FTPLib
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(FTPLib));

        string ftpServerIP;
        string ftpUserID;
        string ftpPassword;
        FtpWebRequest reqFTP;

        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
        }

        //連接FTP
        private void Connect(String path)
        {
            //根據URL創建FTP WebRequest物件
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

            //指定數據傳輸類型
            reqFTP.UseBinary = true;

            //FTP用戶名和密碼
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        }

        public FTPLib(string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            this.ftpServerIP = ftpServerIP;

            this.ftpUserID = ftpUserID;

            this.ftpPassword = ftpPassword;
        }

        //下面的代碼示例瞭如何從FTP服務器上獲得文件列表
        private string[] GetFileList(string path, string WRMethods)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();

            try
            {
                Connect(path);

                reqFTP.Method = WRMethods;

                WebResponse response = reqFTP.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default); //中文文件名

                string line = reader.ReadLine();

                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }

                // to remove the trailing '\n'
                result.Remove(result.ToString().LastIndexOf('\n'), 1);

                reader.Close();
                response.Close();

                return result.ToString().Split('\n');
            }

            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);

                downloadFiles = null;

                return downloadFiles;
            }
        }

        //下面的代碼實現了從FTP服務器上傳文件的功\u-32515 能
        public bool Upload(string filename, string newfilename, string dirname)
        {
            bool retValue = false;

            try
            {
                FileInfo fileInf = new FileInfo(filename);

                //文件名稱為上傳文件原來的名稱
                //string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

                //上傳文件名稱改為新的文件名稱
                string uri = "ftp://" + ftpServerIP + "/" + dirname + "/" + newfilename;

                //連接
                Connect(uri);

                //默認為TRUE,連接不會被關閉
                //在一個命令之後被執行
                reqFTP.KeepAlive = false;

                //執行什麼命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                //上傳文件時通知服務器文件的大小
                reqFTP.ContentLength = fileInf.Length;

                //緩衝大小設置為kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];

                int contentLen;

                //打開一個文件流(System.IO.FileStream)去讀取上傳的文件
                FileStream fs = fileInf.OpenRead();

                //把上傳的文件寫入流
                Stream strm = reqFTP.GetRequestStream();

                //每次讀文件流的KB
                contentLen = fs.Read(buff, 0, buffLength);

                //流內容沒有結束
                while (contentLen != 0)
                {
                    //把內容從FILE STREAM 寫入UPLOAD STREAM
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                //關閉兩個流
                strm.Close();

                fs.Close();

                retValue = true;
            }
            catch (Exception ex)
            {
                retValue = false;
                MessageBox.Show(ex.Message, "Upload Error");
            }

            return retValue;
        }
        public bool CheckFileNameExists(string filePath, string fileName, out string errorinfo)
        {
            bool retValue = false;
            try
            {
                String onlyFileName = Path.GetFileName(fileName);

                string newFileName = filePath + "\\" + onlyFileName;

                if (File.Exists(newFileName))
                {
                    errorinfo = string.Format("本地文件{0}已存在,", newFileName);
                    return true;
                }
                else
                    errorinfo = "";
            }
            catch (Exception ex)
            {
                retValue = false;
                errorinfo = string.Format("因{0},無法下載uc1", ex.Message);
            }
            return retValue;
        }
        //下面的代碼實現了從FTP服務器下載文件的功\u-32515 能
        public bool Download(string filePath, string fileName, out string errorinfo)
        {
            bool retValue = false;

            try
            {
                String onlyFileName = Path.GetFileName(fileName);

                string newFileName = filePath + "\\" + onlyFileName;

                //if (File.Exists(newFileName))
                //{
                //    errorinfo = string.Format("本地文件{0}已存在,無法下載", newFileName);
                //    return false;
                //}

                string url = "ftp://" + ftpServerIP + "/" + fileName;
                //連接
                Connect(url);

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                FileStream outputStream = new FileStream(newFileName, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();

                errorinfo = "";

                retValue = true;
            }
            catch (Exception ex)
            {
                retValue = false;
                errorinfo = string.Format("因{0},無法下載uc1", ex.Message);
            }

            return retValue;
        }

        //刪除文件
        public void DeleteFileName(string fileName)
        {
            try
            {
                FileInfo fileInf = new FileInfo(fileName);

                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

                //連接
                Connect(uri);

                //默認為TRUE,連接不會被關閉
                //在一個命令之後被執行
                reqFTP.KeepAlive = false;

                //執行執行什麼命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "刪除錯誤");
            }
        }

        //創建目錄
        public bool MakeDir(string dirName)
        {
            bool retValue = false;

            try
            {
                if (!DirectoryExist(dirName))
                {
                    string uri = "ftp://" + ftpServerIP + "/" + dirName;
                    //連接
                    Connect(uri);

                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                    response.Close();
                }

                retValue = true;
            }
            catch (Exception ex)
            {
                retValue = false;
                MessageBox.Show(ex.Message);
            }

            return retValue;
        }

        //刪除目錄
        public void delDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + dirName;
                //連接
                Connect(uri);

                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //獲得文件大小
        public long GetFileSize(string filename)
        {
            long fileSize = 0;

            try
            {
                FileInfo fileInf = new FileInfo(filename);

                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

                //連接
                Connect(uri);

                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                fileSize = response.ContentLength;

                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return fileSize;
        }

        //文件改名
        public void Rename(string currentFilename, string newFilename)
        {
            try
            {
                FileInfo fileInf = new FileInfo(currentFilename);

                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                //連接
                Connect(uri);

                reqFTP.Method = WebRequestMethods.Ftp.Rename;

                reqFTP.RenameTo = newFilename;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                //Stream ftpStream = response.GetResponseStream();

                //ftpStream.Close();

                response.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //下面的代碼示例瞭如何從FTP服務器上獲得文件列表
        public string[] GetFileList(string path)
        {
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
        }

        //下面的代碼示例瞭如何從FTP服務器上獲得文件列表
        public string[] GetFileList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
        }

        //獲得文件明細
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        }

        //獲得文件明細
        public string[] GetFilesDetailList(string path)
        {
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
        }

        #region "獲取目錄文件信息"
        /// <summary>
        /// 列出FTP服務u22120 器上面當u21069 前目錄u30340 的所有文件和目錄par         /// </summary>
        public FileStruct[] ListFilesAndDirectories(string path)
        {
            Connect(path);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            FtpWebResponse Response = null;
            Response = (FtpWebResponse)reqFTP.GetResponse();

            //Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
            StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
            string Datastring = stream.ReadToEnd();
            FileStruct[] list = GetList(Datastring);
            return list;
        }
        /// <summary>
        /// 獲取FTP服務器上面當前目錄的所有文件
        /// </summary>
        public FileStruct[] ListFiles()
        {
            FileStruct[] listAll = ListFilesAndDirectories("ftp://" + ftpServerIP + "/");
            List<FileStruct> listFile = new List<FileStruct>();
            foreach (FileStruct file in listAll)
            {
                if (!file.IsDirectory)
                {
                    listFile.Add(file);
                }
            }
            return listFile.ToArray();
        }

        /// <summary>
        /// 獲取FTP服務器上面當前目錄的所有目錄
        /// </summary>
        public FileStruct[] ListDirectories()
        {
            FileStruct[] listAll = ListFilesAndDirectories("ftp://" + ftpServerIP + "/");
            List<FileStruct> listDirectory = new List<FileStruct>();
            foreach (FileStruct file in listAll)
            {
                if (file.IsDirectory)
                {
                    listDirectory.Add(file);
                }
            }
            return listDirectory.ToArray();
        }

        /// <summary>
        /// 獲取文件和目錄列表
        /// </summary>
        /// <param name="datastring">FTP返回的列表字符信息</param>
        private FileStruct[] GetList(string datastring)
        {
            List<FileStruct> myListArray = new List<FileStruct>();
            string[] dataRecords = datastring.Split('\n');
            FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
            foreach (string s in dataRecords)
            {
                if (_directoryListStyle != FileListStyle.Unknown && s != "")
                {
                    FileStruct f = new FileStruct();
                    f.Name = "..";
                    switch (_directoryListStyle)
                    {
                        case FileListStyle.UnixStyle:
                            f = ParseFileStructFromUnixStyleRecord(s);
                            break;
                        case FileListStyle.WindowsStyle:
                            f = ParseFileStructFromWindowsStyleRecord(s);
                            break;
                    }
                    if (!(f.Name == "." || f.Name == ".."))
                    {
                        myListArray.Add(f);
                    }
                }
            }
            return myListArray.ToArray();
        }

        /// <summary>
        /// 從Windows格式中返回文件信息
        /// </summary>
        /// <param name="Record">文件信息</param>
        private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
        {
            FileStruct f = new FileStruct();
            string processstr = Record.Trim();
            string dateStr = processstr.Substring(0, 8);
            processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
            string timeStr = processstr.Substring(0, 7);
            processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
            DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
            myDTFI.ShortTimePattern = "t";
            f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
            if (processstr.Substring(0, 5) == "<DIR>")
            {
                f.IsDirectory = true;
                processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
            }
            else
            {
                string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);   // true);
                processstr = strs[1];
                f.IsDirectory = false;
            }
            f.Name = processstr;
            return f;
        }
        /// <summary>
        /// 判斷文件列表的方式Window方式還是Unix方式
        /// </summary>
        /// <param name="recordList">文件信息列表</param>
        private FileListStyle GuessFileListStyle(string[] recordList)
        {
            foreach (string s in recordList)
            {
                if (s.Length > 10 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
                {
                    return FileListStyle.UnixStyle;
                }
                else if (s.Length > 8 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
                {
                    return FileListStyle.WindowsStyle;
                }
            }
            return FileListStyle.Unknown;
        }

        /// <summary>
        /// 從Unix格式中返回文件信息
        /// </summary>
        /// <param name="Record">文件信息</param>
        private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
        {
            FileStruct f = new FileStruct();
            string processstr = Record.Trim();
            f.Flags = processstr.Substring(0, 10);
            f.IsDirectory = (f.Flags[0] == 'd');
            processstr = (processstr.Substring(11)).Trim();
            _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);   //跳過一部分
            f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
            f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
            _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);   //跳過一部分
            string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
            if (yearOrTime.IndexOf(":") >= 0)  //time
            {
                processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
            }
            f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8));
            f.Name = processstr;   //最後就是名稱
            return f;
        }

        /// <summary>
        /// 按照一定的規則進行字符串截取
        /// </summary>
        /// <param name="s">截取的字符串</param>
        /// <param name="c">查找的字符</param>
        /// <param name="startIndex">查找的位置</param>
        private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
        {
            int pos1 = s.IndexOf(c, startIndex);
            string retString = s.Substring(0, pos1);
            s = (s.Substring(pos1)).Trim();
            return retString;
        }

        #endregion

        #region "判斷目錄或文件是否存在"
        /// <summary>
        /// 判斷當前目錄下指定的子目錄是否存在
        /// </summary>
        /// <param name="RemoteDirectoryName">指定的目錄名</param>
        public bool DirectoryExist(string RemoteDirectoryName)
        {
            try
            {
                if (!IsValidPathChars(RemoteDirectoryName))
                {
                    throw new Exception("目錄名含有無法解析的字符,請確認!");
                }

                FileStruct[] listDir = ListDirectories();
                foreach (FileStruct dir in listDir)
                {
                    if (dir.Name == RemoteDirectoryName)
                    {
                        return true;
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 判斷一個遠程文件是否存在服務器當前目錄下面
        /// </summary>
        /// <param name="RemoteFileName">遠程文件名</param>
        public bool FileExist(string RemoteFileName)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName))
                {
                    throw new Exception("文件名含有無法解析的字符,請確認!");
                }
                FileStruct[] listFile = ListFiles();
                foreach (FileStruct file in listFile)
                {
                    if (file.Name == RemoteFileName)
                    {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "文件,目錄名稱有效性判斷"
        /// <summary>
        /// 判斷目錄名中字符是否合法
        /// </summary>
        /// <param name="DirectoryName">目錄名稱</param>
        public bool IsValidPathChars(string DirectoryName)
        {
            char[] invalidPathChars = Path.GetInvalidPathChars();
            char[] DirChar = DirectoryName.ToCharArray();
            foreach (char C in DirChar)
            {
                if (Array.BinarySearch(invalidPathChars, C) >= 0)
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 判斷文件名中字符是否合法
        /// </summary>
        /// <param name="FileName">文件名稱</param>
        public bool IsValidFileChars(string FileName)
        {
            char[] invalidFileChars = Path.GetInvalidFileNameChars();
            char[] NameChar = FileName.ToCharArray();
            foreach (char C in NameChar)
            {
                if (Array.BinarySearch(invalidFileChars, C) >= 0)
                {
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region "註釋"
        /*
        #region 刪除文件
        /// <summary>
        /// 從TP服務u22120 器上面刪u-27036 除一個u25991 文件
        /// </summary>
        /// <param name="RemoteFileName">遠uc2程文件名</param>
        public void DeleteFile(string RemoteFileName)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName))
                {
                    throw new Exception("文件名非法!");
                }
                Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DeleteFile);
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion

        #region 重命名文件
        /// <summary>
        /// 更改一個u25991 文件的名稱u25110 或一個u30446 目錄u30340 的名稱par         /// </summary>
        /// <param name="RemoteFileName">原始文件或目錄u21517 名稱uc1</param>
        /// <param name="NewFileName">新的文件或目錄u30340 的名稱uc1</param>
        public bool ReName(string RemoteFileName, string NewFileName)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(NewFileName))
                {
                    throw new Exception("文件名非法!");
                }
                if (RemoteFileName == NewFileName)
                {
                    return true;
                }
                if (FileExist(RemoteFileName))
                {
                    Request = OpenRequest(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.Rename);
                    Request.RenameTo = NewFileName;
                    Response = (FtpWebResponse)Request.GetResponse();

                }
                else
                {
                    throw new Exception("文件在服務u22120 器上不存在!");
                }
                return true;
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion

        #region 拷貝u12289 、移動u25991 文件
        /// <summary>
        /// 把當u21069 前目錄u19979 下面的一個u25991 文件拷貝u21040 到服務u22120 器上面另外的目錄u20013 中,注意,拷貝u25991 文件之後,當u21069 前工作目錄u-28712 ?是文件原來u25152 所在的目錄par         /// </summary>
        /// <param name="RemoteFile">當uc2前目錄u19979 下的文件名</param>
        /// <param name="DirectoryName">新目錄u21517 名稱u12290 。
        /// 說uc2明:如果新目錄u26159 是當u21069 前目錄u30340 的子目錄u-244 ,則u30452 直接指定子目錄u12290 。如: SubDirectory1/SubDirectory2 ;
        /// 如果新目錄u19981 不是當u21069 前目錄u30340 的子目錄u-244 ,則u24517 必須u20174 ?根目錄u19968 一級u19968 一級u30340 的指定。如:./NewDirectory/SubDirectory1/SubDirectory2
        /// </param>
        /// <returns></returns>
        public bool CopyFileToAnotherDirectory(string RemoteFile, string DirectoryName)
        {
            string CurrentWorkDir = this.DirectoryPath;
            try
            {
                byte[] bt = DownloadFile(RemoteFile);
                GotoDirectory(DirectoryName);
                bool Success = UploadFile(bt, RemoteFile, false);
                this.DirectoryPath = CurrentWorkDir;
                return Success;
            }
            catch (Exception ep)
            {
                this.DirectoryPath = CurrentWorkDir;
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        /// <summary>
        /// 把當u21069 前目錄u19979 下面的一個u25991 文件移動u21040 到服務u22120 器上面另外的目錄u20013 中,注意,移動u25991 文件之後,當u21069 前工作目錄u-28712 ?是文件原來u25152 所在的目錄par         /// </summary>
        /// <param name="RemoteFile">當uc2前目錄u19979 下的文件名</param>
        /// <param name="DirectoryName">新目錄u21517 名稱u12290 。
        /// 說uc2明:如果新目錄u26159 是當u21069 前目錄u30340 的子目錄u-244 ,則u30452 直接指定子目錄u12290 。如: SubDirectory1/SubDirectory2 ;
        /// 如果新目錄u19981 不是當u21069 前目錄u30340 的子目錄u-244 ,則u24517 必須u20174 ?根目錄u19968 一級u19968 一級u30340 的指定。如:./NewDirectory/SubDirectory1/SubDirectory2
        /// </param>
        /// <returns></returns>
        public bool MoveFileToAnotherDirectory(string RemoteFile, string DirectoryName)
        {
            string CurrentWorkDir = this.DirectoryPath;
            try
            {
                if (DirectoryName == "")
                    return false;
                if (!DirectoryName.StartsWith("/"))
                    DirectoryName = "/" + DirectoryName;
                if (!DirectoryName.EndsWith("/"))
                    DirectoryName += "/";
                bool Success = ReName(RemoteFile, DirectoryName + RemoteFile);
                this.DirectoryPath = CurrentWorkDir;
                return Success;
            }
            catch (Exception ep)
            {
                this.DirectoryPath = CurrentWorkDir;
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion

        #region 建立、刪u-27036 除子目錄par         /// <summary>
        /// 在FTP服務u22120 器上當u21069 前工作目錄u24314 建立一個u23376 子目錄par         /// </summary>
        /// <param name="DirectoryName">子目錄u21517 名稱uc1</param>
        public bool MakeDirectory(string DirectoryName)
        {
            try
            {
                if (!IsValidPathChars(DirectoryName))
                {
                    throw new Exception("目錄u21517 名非法!");
                }
                if (DirectoryExist(DirectoryName))
                {
                    throw new Exception("服務u22120 器上面已經u23384 存在同名的文件名或目錄u21517 名!");
                }
                Response = Open(new Uri(this.Uri.ToString() + DirectoryName), WebRequestMethods.Ftp.MakeDirectory);
                return true;
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        /// <summary>
        /// 從當前工作目錄u20013 中刪u-27036 除一個u23376 子目錄par         /// </summary>
        /// <param name="DirectoryName">子目錄u21517 名稱uc1</param>
        public bool RemoveDirectory(string DirectoryName)
        {
            try
            {
                if (!IsValidPathChars(DirectoryName))
                {
                    throw new Exception("目錄u21517 名非法!");
                }
                if (!DirectoryExist(DirectoryName))
                {
                    throw new Exception("服務u22120 器上面不存在指定的文件名或目錄u21517 名!");
                }
                Response = Open(new Uri(this.Uri.ToString() + DirectoryName), WebRequestMethods.Ftp.RemoveDirectory);
                return true;
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
        #endregion

        #region 目錄u20999 切換u25805 操作
        /// <summary>
        /// 進uc2入一個u30446 目錄par         /// </summary>
        /// <param name="DirectoryName">
        /// 新目錄u30340 的名字。
        /// 說明:如果新目錄u26159 是當u21069 前目錄u30340 的子目錄u-244 ,則u30452 直接指定子目錄u12290 。如: SubDirectory1/SubDirectory2 ;
        /// 如果新目錄u19981 不是當u21069 前目錄u30340 的子目錄u-244 ,則u24517 必須u20174 ?根目錄u19968 一級u19968 一級u30340 的指定。如:./NewDirectory/SubDirectory1/SubDirectory2
        /// </param>
        public bool GotoDirectory(string DirectoryName)
        {
            string CurrentWorkPath = this.DirectoryPath;
            try
            {
                DirectoryName = DirectoryName.Replace("\\", "/");
                string[] DirectoryNames = DirectoryName.Split(new char[] { '/' });
                if (DirectoryNames[0] == ".")
                {
                    this.DirectoryPath = "/";
                    if (DirectoryNames.Length == 1)
                    {
                        return true;
                    }
                    Array.Clear(DirectoryNames, 0, 1);
                }
                bool Success = false;
                foreach (string dir in DirectoryNames)
                {
                    if (dir != null)
                    {
                        Success = EnterOneSubDirectory(dir);
                        if (!Success)
                        {
                            this.DirectoryPath = CurrentWorkPath;
                            return false;
                        }
                    }
                }
                return Success;

            }
            catch (Exception ep)
            {
                this.DirectoryPath = CurrentWorkPath;
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }

        /// <summary>
        /// 從當前工作目錄u-28709 ?入一個u23376 子目錄par         /// </summary>
        /// <param name="DirectoryName">子目錄u21517 名稱uc1</param>
        private bool EnterOneSubDirectory(string DirectoryName)
        {
            try
            {
                if (DirectoryName.IndexOf("/") >= 0 || !IsValidPathChars(DirectoryName))
                {
                    throw new Exception("目錄u21517 名非法!");
                }
                if (DirectoryName.Length > 0 && DirectoryExist(DirectoryName))
                {
                    if (!DirectoryName.EndsWith("/"))
                    {
                        DirectoryName += "/";
                    }
                    _DirectoryPath += DirectoryName;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }

        /// <summary>
        /// 從當前工作目錄u24448 往上一級u30446 目錄par         /// </summary>
        public bool ComeoutDirectory()
        {
            if (_DirectoryPath == "/")
            {
                ErrorMsg = "當uc2前目錄u24050 已經u26159 是根目錄u-255 !";
                throw new Exception("當前目錄u24050 已經u26159 是根目錄u-255 !");
            }
            char[] sp = new char[1] { '/' };

            string[] strDir = _DirectoryPath.Split(sp, StringSplitOptions.RemoveEmptyEntries);
            if (strDir.Length == 1)
            {
                _DirectoryPath = "/";
            }
            else
            {
                _DirectoryPath = String.Join("/", strDir, 0, strDir.Length - 1);
            }
            return true;

        }
        #endregion
        */
        #endregion
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章