"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Reliably Parse Variably Formatted FTP Directory Listings in C#?

How Can I Reliably Parse Variably Formatted FTP Directory Listings in C#?

Posted on 2025-03-23
Browse:409

How Can I Reliably Parse Variably Formatted FTP Directory Listings in C#?

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 (|\\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 != "") ? 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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3