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
    }
}
 

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