/// <summary> /// 在FTP服务器上删除一个选项 /// </summary> public void DeleteItemOnFTPServer(FTPFileSystem fileSystem) { //检查子目录是否存在 bool urlExist = VerifyFTPUrlExist(fileSystem.Url); if (!urlExist) { return; } try { //不为空的文件夹不能删除 if (fileSystem.IsDirectory) { var subFTPFiles = GetSubDirectoriesAndFiles(fileSystem.Url); DeleteItemsOnFTPServer(subFTPFiles); } //创建一个FtpWebRequest创建子目录 FtpWebRequest request = WebRequest.Create(fileSystem.Url) as FtpWebRequest; request.Credentials = this.Credentials; request.Method = fileSystem.IsDirectory ? WebRequestMethods.Ftp.RemoveDirectory : WebRequestMethods.Ftp.DeleteFile; using (FtpWebResponse response = request.GetResponse() as FtpWebResponse) { this.OnNewMessageArrived(new NewMessageEventArg { NewMessage = response.StatusDescription }); } } catch (System.Net.WebException webEx) { FtpWebResponse ftpResponse = webEx.Response as FtpWebResponse; string msg = string.Format( "There is an error while deleting {0}. " + " StatusCode: {1} StatusDescription: {2} ", fileSystem.Url.ToString(), ftpResponse.StatusCode.ToString(), ftpResponse.StatusDescription); ApplicationException errorException = new ApplicationException(msg, webEx); //有错误时执行ErrorOccurred 事件 ErrorEventArgs e = new ErrorEventArgs { ErrorException = errorException }; this.OnErrorOccurred(e); } }
/// <summary> /// Delete an item on FTP server. /// </summary> public void DeleteItemOnFTPServer(FTPFileSystem fileSystem) { // Check whether sub directory exist. bool urlExist = VerifyFTPUrlExist(fileSystem.Url); if (!urlExist) { return; } try { // Non-Empty folder cannot be deleted. if (fileSystem.IsDirectory) { var subFTPFiles = GetSubDirectoriesAndFiles(fileSystem.Url); DeleteItemsOnFTPServer(subFTPFiles); } // Create an FtpWebRequest to create the sub directory. FtpWebRequest request = WebRequest.Create(fileSystem.Url) as FtpWebRequest; request.Credentials = this.Credentials; request.Method = fileSystem.IsDirectory ? WebRequestMethods.Ftp.RemoveDirectory : WebRequestMethods.Ftp.DeleteFile; using (FtpWebResponse response = request.GetResponse() as FtpWebResponse) { this.OnNewMessageArrived(new NewMessageEventArg { NewMessage = response.StatusDescription }); } } catch (System.Net.WebException webEx) { FtpWebResponse ftpResponse = webEx.Response as FtpWebResponse; string msg = string.Format( "There is an error while deleting {0}. " + " StatusCode: {1} StatusDescription: {2} ", fileSystem.Url.ToString(), ftpResponse.StatusCode.ToString(), ftpResponse.StatusDescription); ApplicationException errorException = new ApplicationException(msg, webEx); // Fire the ErrorOccurred event with the error. ErrorEventArgs e = new ErrorEventArgs { ErrorException = errorException }; this.OnErrorOccurred(e); } }
/// <summary> /// 得到子目录和路径中文件,在枚举中使用所有文件夹 /// 当运行FTP LIST 协议方法得到详细的文件列表。 /// 在一个FTP服务器上,服务器响应许多信息记录,每个记录代表一个文件 /// </summary> public IEnumerable <FTPFileSystem> GetSubDirectoriesAndFiles(Uri url) { FtpWebRequest request = WebRequest.Create(url) as FtpWebRequest; request.Credentials = this.Credentials; request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = null; Stream responseStream = null; StreamReader reader = null; try { response = request.GetResponse() as FtpWebResponse; this.OnNewMessageArrived(new NewMessageEventArg { NewMessage = response.StatusDescription }); responseStream = response.GetResponseStream(); reader = new StreamReader(responseStream); List <FTPFileSystem> subDirs = new List <FTPFileSystem>(); string subDir = reader.ReadLine(); //从记录字符串中找出FTP目录列表格式 FTPDirectoryListingStyle style = FTPDirectoryListingStyle.MSDOS; if (!string.IsNullOrEmpty(subDir)) { style = FTPFileSystem.GetDirectoryListingStyle(subDir); } while (!string.IsNullOrEmpty(subDir)) { subDirs.Add(FTPFileSystem.ParseRecordString(url, subDir, style)); subDir = reader.ReadLine(); } return(subDirs); } finally { if (response != null) { response.Close(); } //关闭StreamReader对象和相关流,释放reader系统资源 if (reader != null) { reader.Close(); } } }
/// <summary> /// Get the sub directories and files of the Url. It will be used in enumerate /// all the folders. /// When run the FTP LIST protocol method to get a detailed listing of the files /// on an FTP server, the server will response many records of information. Each /// record represents a file. /// </summary> public IEnumerable <FTPFileSystem> GetSubDirectoriesAndFiles(Uri url) { FtpWebRequest request = WebRequest.Create(url) as FtpWebRequest; request.Credentials = this.Credentials; request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = null; Stream responseStream = null; StreamReader reader = null; try { response = request.GetResponse() as FtpWebResponse; this.OnNewMessageArrived(new NewMessageEventArg { NewMessage = response.StatusDescription }); responseStream = response.GetResponseStream(); reader = new StreamReader(responseStream); List <FTPFileSystem> subDirs = new List <FTPFileSystem>(); string subDir = reader.ReadLine(); // Find out the FTP Directory Listing Style from the recordString. FTPDirectoryListingStyle style = FTPDirectoryListingStyle.MSDOS; if (!string.IsNullOrEmpty(subDir)) { style = FTPFileSystem.GetDirectoryListingStyle(subDir); } while (!string.IsNullOrEmpty(subDir)) { subDirs.Add(FTPFileSystem.ParseRecordString(url, subDir, style)); subDir = reader.ReadLine(); } return(subDirs); } finally { if (response != null) { response.Close(); } // Close the StreamReader object and the underlying stream, and release // any system resources associated with the reader. if (reader != null) { reader.Close(); } } }
/// <summary> /// Get an FTPFileSystem from the recordString. /// </summary> public static FTPFileSystem ParseRecordString(Uri baseUrl, string recordString, FTPDirectoryListingStyle type) { FTPFileSystem fileSystem = null; if (type == FTPDirectoryListingStyle.UNIX) { fileSystem = ParseUNIXRecordString(recordString); } else { fileSystem = ParseMSDOSRecordString(recordString); } // Add "/" to the url if it is a directory fileSystem.Url = new Uri(baseUrl, fileSystem.Name + (fileSystem.IsDirectory ? "/" : string.Empty)); return(fileSystem); }
/// <summary> /// 记录字符串如下: /// Directory: drwxrwxrwx 1 owner group 0 Dec 13 11:25 Folder A /// File: -rwxrwxrwx 1 owner group 1024 Dec 13 11:25 File B /// NOTE: The date segment does not contains year. /// </summary> static FTPFileSystem ParseUNIXRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.UNIX; // The segments is like "drwxrwxrwx", "", "", "1", "owner", "", "", "", // "group", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // "0", "Dec", "13", "11:25", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; //许可部分如"drwxrwxrwx string permissionsegment = segments[index]; //如果属性以“d”开始,意味是个目录 fileSystem.IsDirectory = permissionsegment[0] == 'd'; //跳过空部分 while (segments[++index] == string.Empty) { } //跳过目录部分 //跳过空部分 while (segments[++index] == string.Empty) { } //跳过所有者部分 //跳过空部分 while (segments[++index] == string.Empty) { } //跳过组部分 //跳过空部分 while (segments[++index] == string.Empty) { } //如果文件流是个文件,大小大于0 fileSystem.Size = int.Parse(segments[index]); //跳过空部分 while (segments[++index] == string.Empty) { } //月份部分 string monthsegment = segments[index]; //跳过空部分 while (segments[++index] == string.Empty) { } // 天部分 string daysegment = segments[index]; //跳过空部分 while (segments[++index] == string.Empty) { } // 时间部分. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0} {1} {2} ", timesegment, monthsegment, daysegment)); //跳过空部分 while (segments[++index] == string.Empty) { } //在原始字符串中计算文件名索引 int filenameIndex = 0; for (int i = 0; i < index; i++) { //在初始字符中' represents ' if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } //文件名可能包括许多部分因为名字包括'' fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return fileSystem; }
/// <summary> /// 12-13-10 12:41PM <DIR> Folder A /// </summary> /// <param name="recordString"></param> /// <returns></returns> static FTPFileSystem ParseMSDOSRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.MSDOS; // The segments is like "12-13-10", "", "12:41PM", "", "","", "", // "", "", "<DIR>", "", "", "", "", "", "", "", "", "", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; //如果四位年在IIS中没被选中,日期部分像"12-13-10"代替"12-13-2010" string dateSegment = segments[index]; string[] dateSegments = dateSegment.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); int month = int.Parse(dateSegments[0]); int day = int.Parse(dateSegments[1]); int year = int.Parse(dateSegments[2]); //如果年大于50小于100是19** if (year >= 50 && year < 100) { year += 1900; } //如果年小于50是20** else if (year < 50) { year += 2000; } //跳过空部分 while (segments[++index] == string.Empty) { } // 时间部分. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0}-{1}-{2} {3}", year, month, day, timesegment)); //跳过空部分 while (segments[++index] == string.Empty) { } //大小或目录部分,如果是“<DIR>”它意味一个目录,否则是文件大小。 string sizeOrDirSegment = segments[index]; fileSystem.IsDirectory = sizeOrDirSegment.Equals("<DIR>", StringComparison.OrdinalIgnoreCase); //如果fileSystem 是一个文件,大小大于0 if (!fileSystem.IsDirectory) { fileSystem.Size = int.Parse(sizeOrDirSegment); } while (segments[++index] == string.Empty) { } //计算在原始字符串中文件名部分的索引 int filenameIndex = 0; for (int i = 0; i < index; i++) { // 在原始字符串中"" represents ' if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } //文件名包括许多部分因为名字能包含' ' fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return fileSystem; }
/// <summary> /// 12-13-10 12:41PM <DIR> Folder A /// </summary> /// <param name="recordString"></param> /// <returns></returns> static FTPFileSystem ParseMSDOSRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.MSDOS; // The segments is like "12-13-10", "", "12:41PM", "", "","", "", // "", "", "<DIR>", "", "", "", "", "", "", "", "", "", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; // The date segment is like "12-13-10" instead of "12-13-2010" if Four-digit years // is not checked in IIS. string dateSegment = segments[index]; string[] dateSegments = dateSegment.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); int month = int.Parse(dateSegments[0]); int day = int.Parse(dateSegments[1]); int year = int.Parse(dateSegments[2]); // If year >=50 and year <100, then it means the year 19** if (year >= 50 && year < 100) { year += 1900; } // If year <50, then it means the year 20** else if (year < 50) { year += 2000; } // Skip the empty segments. while (segments[++index] == string.Empty) { } // The time segment. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0}-{1}-{2} {3}", year, month, day, timesegment)); // Skip the empty segments. while (segments[++index] == string.Empty) { } // The size or directory segment. // If this segment is "<DIR>", then it means a directory, else it means the // file size. string sizeOrDirSegment = segments[index]; fileSystem.IsDirectory = sizeOrDirSegment.Equals("<DIR>", StringComparison.OrdinalIgnoreCase); // If this fileSystem is a file, then the size is larger than 0. if (!fileSystem.IsDirectory) { fileSystem.Size = int.Parse(sizeOrDirSegment); } // Skip the empty segments. while (segments[++index] == string.Empty) { } // Calculate the index of the file name part in the original string. int filenameIndex = 0; for (int i = 0; i < index; i++) { // "" represents ' ' in the original string. if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } // The file name may include many segments because the name can contain ' '. fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return(fileSystem); }
/// <summary> /// The recordString is like /// Directory: drwxrwxrwx 1 owner group 0 Dec 13 11:25 Folder A /// File: -rwxrwxrwx 1 owner group 1024 Dec 13 11:25 File B /// NOTE: The date segment does not contains year. /// </summary> static FTPFileSystem ParseUNIXRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.UNIX; // The segments is like "drwxrwxrwx", "", "", "1", "owner", "", "", "", // "group", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // "0", "Dec", "13", "11:25", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; // The permission segment is like "drwxrwxrwx". string permissionsegment = segments[index]; // If the property start with 'd', then it means a directory. fileSystem.IsDirectory = permissionsegment[0] == 'd'; // Skip the empty segments. while (segments[++index] == string.Empty) { } // Skip the directories segment. // Skip the empty segments. while (segments[++index] == string.Empty) { } // Skip the owner segment. // Skip the empty segments. while (segments[++index] == string.Empty) { } // Skip the group segment. // Skip the empty segments. while (segments[++index] == string.Empty) { } // If this fileSystem is a file, then the size is larger than 0. fileSystem.Size = int.Parse(segments[index]); // Skip the empty segments. while (segments[++index] == string.Empty) { } // The month segment. string monthsegment = segments[index]; // Skip the empty segments. while (segments[++index] == string.Empty) { } // The day segment. string daysegment = segments[index]; // Skip the empty segments. while (segments[++index] == string.Empty) { } // The time segment. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0} {1} {2} ", timesegment, monthsegment, daysegment)); // Skip the empty segments. while (segments[++index] == string.Empty) { } // Calculate the index of the file name part in the original string. int filenameIndex = 0; for (int i = 0; i < index; i++) { // "" represents ' ' in the original string. if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } // The file name may include many segments because the name can contain ' '. fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return(fileSystem); }
/// <summary> /// 12-13-10 12:41PM <DIR> Folder A /// </summary> /// <param name="recordString"></param> /// <returns></returns> static FTPFileSystem ParseMSDOSRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.MSDOS; // The segments is like "12-13-10", "", "12:41PM", "", "","", "", // "", "", "<DIR>", "", "", "", "", "", "", "", "", "", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; //如果四位年在IIS中没被选中,日期部分像"12-13-10"代替"12-13-2010" string dateSegment = segments[index]; string[] dateSegments = dateSegment.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); int month = int.Parse(dateSegments[0]); int day = int.Parse(dateSegments[1]); int year = int.Parse(dateSegments[2]); //如果年大于50小于100是19** if (year >= 50 && year < 100) { year += 1900; } //如果年小于50是20** else if (year < 50) { year += 2000; } //跳过空部分 while (segments[++index] == string.Empty) { } // 时间部分. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0}-{1}-{2} {3}", year, month, day, timesegment)); //跳过空部分 while (segments[++index] == string.Empty) { } //大小或目录部分,如果是“<DIR>”它意味一个目录,否则是文件大小。 string sizeOrDirSegment = segments[index]; fileSystem.IsDirectory = sizeOrDirSegment.Equals("<DIR>", StringComparison.OrdinalIgnoreCase); //如果fileSystem 是一个文件,大小大于0 if (!fileSystem.IsDirectory) { fileSystem.Size = int.Parse(sizeOrDirSegment); } while (segments[++index] == string.Empty) { } //计算在原始字符串中文件名部分的索引 int filenameIndex = 0; for (int i = 0; i < index; i++) { // 在原始字符串中"" represents ' if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } //文件名包括许多部分因为名字能包含' ' fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return(fileSystem); }
/// <summary> /// 记录字符串如下: /// Directory: drwxrwxrwx 1 owner group 0 Dec 13 11:25 Folder A /// File: -rwxrwxrwx 1 owner group 1024 Dec 13 11:25 File B /// NOTE: The date segment does not contains year. /// </summary> static FTPFileSystem ParseUNIXRecordString(string recordString) { FTPFileSystem fileSystem = new FTPFileSystem(); fileSystem.OriginalRecordString = recordString.Trim(); fileSystem.DirectoryListingStyle = FTPDirectoryListingStyle.UNIX; // The segments is like "drwxrwxrwx", "", "", "1", "owner", "", "", "", // "group", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // "0", "Dec", "13", "11:25", "Folder", "A". string[] segments = fileSystem.OriginalRecordString.Split(' '); int index = 0; //许可部分如"drwxrwxrwx string permissionsegment = segments[index]; //如果属性以“d”开始,意味是个目录 fileSystem.IsDirectory = permissionsegment[0] == 'd'; //跳过空部分 while (segments[++index] == string.Empty) { } //跳过目录部分 //跳过空部分 while (segments[++index] == string.Empty) { } //跳过所有者部分 //跳过空部分 while (segments[++index] == string.Empty) { } //跳过组部分 //跳过空部分 while (segments[++index] == string.Empty) { } //如果文件流是个文件,大小大于0 fileSystem.Size = int.Parse(segments[index]); //跳过空部分 while (segments[++index] == string.Empty) { } //月份部分 string monthsegment = segments[index]; //跳过空部分 while (segments[++index] == string.Empty) { } // 天部分 string daysegment = segments[index]; //跳过空部分 while (segments[++index] == string.Empty) { } // 时间部分. string timesegment = segments[index]; fileSystem.ModifiedTime = DateTime.Parse(string.Format("{0} {1} {2} ", timesegment, monthsegment, daysegment)); //跳过空部分 while (segments[++index] == string.Empty) { } //在原始字符串中计算文件名索引 int filenameIndex = 0; for (int i = 0; i < index; i++) { //在初始字符中' represents ' if (segments[i] == string.Empty) { filenameIndex += 1; } else { filenameIndex += segments[i].Length + 1; } } //文件名可能包括许多部分因为名字包括'' fileSystem.Name = fileSystem.OriginalRecordString.Substring(filenameIndex).Trim(); return(fileSystem); }