Home >Backend Development >C++ >How Can I Parse FTP ListDirectoryDetails Responses in C# to Extract File Information Reliably?
Parsing FTP ListDirectoryDetails Responses with C#
When monitoring FTP locations for updates, it's essential to extract information from the responses returned by the WebRequestMethods.Ftp.ListDirectoryDetails method. However, different FTP server software presents varying response formats, posing a parsing challenge.
Problem Statement
Given the two common response formats (DOS/Windows and *nix), the task is to find a fully managed C# class that seamlessly handles these differences and extracts the following details:
Answer
DOS/Windows Listings
For the first response format (DOS/Windows), the following C# code effectively parses the response:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/"); request.Credentials = new NetworkCredential("user", "password"); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()); 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 code will produce the desired output:
Version2 size = 0 modified = 2011-08-10 12:02 image34.gif size = 144700153 modified = 2009-06-25 14:41 updates.txt size = 144700153 modified = 2009-06-25 14:51 digger.tif size = 144700214 modified = 2010-11-04 14:45
Other (*nix) Listings
For other *nix listings, using the MLSD command is recommended. MLSD returns a machine-readable listing format, eliminating the need for complex parsing.
Alternative Libraries
Using the FtpWebRequest class can be unreliable for this purpose. Consider using third-party libraries like WinSCP .NET assembly, which supports MLSD and can fall back to the LIST command to handle various response formats.
The above is the detailed content of How Can I Parse FTP ListDirectoryDetails Responses in C# to Extract File Information Reliably?. For more information, please follow other related articles on the PHP Chinese website!