Parsing FTP Responses for Directory Listing with Variable Formats Using C#
Problem Statement:
In developing a service to monitor FTP locations, it becomes necessary to parse the response received from a FtpWebRequest using the WebRequestMethods.Ftp.ListDirectoryDetails method. The challenge arises due to variations in response formats across FTP server software. For instance, one server might return a response in a Windows-style DOS format, while another might adhere to a Linux-style UNIX format.
Custom C# Parsing Solution:
Although the FtpWebRequest class does not natively handle these format variations, one can create a custom C# solution. For the DOS-style format, the following code can be utilized:
string pattern = "^(\d+-\d+-\d+\s+\d+:\d+(\w{2}))\s+(<DIR>|\d+)\s+(.*)$"; Regex regex = new Regex(pattern); while (!reader.EndOfStream) { string line = reader.ReadLine(); Match match = regex.Match(line); string s = match.Groups[1].Value; DateTime modified = DateTime.ParseExact(s, "MM-dd-yy hh:mmtt", culture, DateTimeStyles.None); s = match.Groups[2].Value; long size = (s != "<DIR>") ? long.Parse(s) : 0; string name = match.Groups[3].Value; Console.WriteLine("{0,-16} {1,9} {2}", name, size, modified); }
Modern Solution Using MLSD Command:
A better approach is to leverage the MLSD command, which is supported by modern FTP servers. This command returns a standardized, machine-readable format for directory listings. Certain third-party libraries, such as WinSCP .NET, support the MLSD command and provide parsed results in a consistent manner.
RemoteFileInfo[] files = session.EnumerateRemoteFiles(path, null); foreach (RemoteFileInfo file in files) { Console.WriteLine("{0,-16} {1,9} {2}", file.Name, file.Length, file.LastWriteTime); }
Conclusion:
Parsing FTP directory listing responses requires careful handling of varying formats. While a custom solution is possible, it is more reliable to utilize libraries that support the modern MLSD command. This approach обеспечивает consistent parsing and simplifies the task of extracting relevant file and directory metadata from FTP responses.
The above is the detailed content of How Can I Reliably Parse Variably Formatted FTP Directory Listings in C#?. For more information, please follow other related articles on the PHP Chinese website!