Parsing FTP Responses with a Flexible C# Class
Managing FTP connections can be a complex task, especially when dealing with diverse response formats. To address this challenge, you can employ the ListDirectoryDetails method of FtpWebRequest, but this can still require parsing and handling variations in responses.
Parsing DOS/Windows-Style Listings
For listings in DOS/Windows format, you can utilize the following code:
string pattern = @"\^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$"; Regex regex = new Regex(pattern); IFormatProvider culture = CultureInfo.GetCultureInfo("en-us"); 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} size = {1,9} modified = {2}", name, size, modified.ToString("yyyy-MM-dd HH:mm")); }
This regex pattern matches timestamps, file/directory sizes, and names for the DOS/Windows style.
UNIX-Style Listings
For UNIX-style listings, consider referring to the responses on Handling MLSD for FTP directories.
An Alternative Option: Modern MLSD Command
Ideally, you can leverage the MLSD command to obtain directory listings in a structured format. This is preferred over parsing the human-readable LIST format. MLSD is supported by many third-party libraries and tools such as WinSCP.
Conclusion
Parsing FTP responses can be complex, but by using the right tools and techniques, you can ensure reliable handling of varying listing formats. Employing a comprehensive tool like WinSCP that supports both MLSD and LIST can provide a more robust and extensible solution for your FTP management needs.
The above is the detailed content of How Can I Efficiently Parse FTP Responses in C# for Different Listing Formats?. For more information, please follow other related articles on the PHP Chinese website!