天天看点

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 "註釋"

        #endregion

    }

}