Home >Backend Development >C++ >How to Efficiently Parse FTP Directory Listings in C#?
Parsing WebRequestMethods.Ftp.ListDirectoryDetails FTP Response in C#
The FtpWebRequest.ListDirectoryDetails method allows the retrieval of detailed information about files and directories in an FTP server. However, parsing the response from this method can be challenging due to the varying formats used by different FTP servers.
Custom Parsing for Different Response Formats
To parse the response seamlessly, a custom C# class can be created that handles the different formats. For example:
string pattern = @"\s+(\d+)(\w+)(\s+|\s*\d+[^ ].+)(.*)"; Regex regex = new Regex(pattern); 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()); while (!reader.EndOfStream) { string line = reader.ReadLine(); Match match = regex.Match(line); if (match.Success) { string fileName = match.Groups[4].Value.Trim(); long size = long.Parse(match.Groups[1].Value); string lastModified = match.Groups[2].Value + " " + match.Groups[3].Value; bool isDirectory = match.Groups[1].Value.StartsWith("d"); Console.WriteLine("{0}\t{1}\t{2}", fileName, lastModified, size); } }
Using a Modern FTP Client with Machine-Readable Response
However, it is recommended to use an FTP client that supports the MLSD command, which returns directory listings in a machine-readable format. Parsing the human-readable LIST command response should be a last resort for outdated servers that do not support MLSD.
Third-party libraries such as WinSCP .NET offer FTP client functionality with support for MLSD and various human-readable listing formats. This simplifies the process of parsing FTP directory listings.
Benefits of Using a Third-Party Library
The above is the detailed content of How to Efficiently Parse FTP Directory Listings in C#?. For more information, please follow other related articles on the PHP Chinese website!