从 FTP 目录读取文件夹路径到 IEnumerable

Read folder paths from FTP directory to IEnumerable

我目前正在开发 .NET 4.6 控制台应用程序。我需要从 FTP 服务器上的不同目录解析几个 XML 文件。我认为最好的方法是读取所有文件路径并将它们存储到 IEnumerable 中,以进一步处理它们(将 XML 文件序列化为对象)。

根 FTP 路径如下所示:

string urlFtpServer = @"ftp://128.0.1.70";

文件路径如下所示:

string file1 = @"ftp://128.0.1.70/MyFolder1/Mainfile.xml";
string file2 = @"ftp://128.0.1.70/MyFolder1/Subfile.xml";
string file3 = @"ftp://128.0.1.70/MyFolder2/Mainfile.xml";
string file4 = @"ftp://128.0.1.70/MyFolder2/Subfile.xml";
string file5 = @"ftp://128.0.1.70/MyFolder3/Mainfile.xml";

我的问题是,你知道我怎样才能得到那些特定的文件路径吗?

我目前可以使用此编码读取 FTP 目录中的文件夹:

static void Main(string[] args)
{
    string url = @"ftp://128.0.1.70";

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

    request.Credentials = new NetworkCredential("My-User", "mypassword");

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    Console.WriteLine(reader.ReadToEnd());

    Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

    reader.Close();
    response.Close();

    Console.ReadKey();
}

你知道我如何从 FTP 主目录读取所有文件路径并可能将它们存储到 List<string> 中吗?

非常感谢!!

使用 FtpWebRequest

FtpWebRequest 没有任何对递归文件操作(包括列表)的明确支持。你必须自己实现递归:

  • 列出远程目录
  • 迭代条目,递归到子目录(再次列出它们等)

棘手的部分是从子目录中识别文件。 FtpWebRequest 无法以可移植的方式做到这一点。不幸的是,FtpWebRequest 不支持 MLSD 命令,这是在 FTP 协议中检索具有文件属性的目录列表的唯一可移植方式。另见 .

您的选择是:

  • 对一个文件名进行操作,该操作肯定对文件失败而对目录成功(反之亦然)。 IE。你可以试试下载"name"。如果成功,它是一个文件,如果失败,它是一个目录。
  • 你可能很幸运,在你的特定情况下,你可以通过文件名从目录中区分文件(即你的所有文件都有扩展名,而子目录没有)
  • 您使用长目录列表(LIST 命令= ListDirectoryDetails 方法)并尝试解析特定于服务器的列表。许多 FTP 服务器使用 *nix 样式列表,您可以在条目的最开头通过 d 识别目录。但是许多服务器使用不同的格式。下面的例子使用了这种方法(假设是 *nix 格式)
void ListFtpDirectory(
    string url, string rootPath, NetworkCredential credentials, List<string> list)
{
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url + rootPath);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    List<string> lines = new List<string>();

    using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (StreamReader listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    foreach (string line in lines)
    {
        string[] tokens =
            line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
        string name = tokens[8];
        string permissions = tokens[0];

        string filePath = rootPath + name;

        if (permissions[0] == 'd')
        {
            ListFtpDirectory(url, filePath + "/", credentials, list);
        }
        else
        {
            list.Add(filePath);
        }
    }
}

使用如下函数:

List<string> list = new List<string>();
NetworkCredential credentials = new NetworkCredential("user", "mypassword");
string url = "ftp://ftp.example.com/";
ListFtpDirectory(url, "", credentials, list);

使用第 3 方库

如果您想避免解析特定于服务器的目录列表格式的麻烦,请使用支持 MLSD 命令的第 3 方库 and/or 解析各种 LIST 列表格式;和递归下载。

例如 WinSCP .NET assembly you can list whole directory with a single call to the Session.EnumerateRemoteFiles:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // List files
    IEnumerable<string> list =
        session.EnumerateRemoteFiles("/", null, EnumerationOptions.AllDirectories).
        Select(fileInfo => fileInfo.FullName);
}

如果服务器支持,WinSCP 在内部使用 MLSD 命令。如果没有,它使用 LIST 命令并支持数十种不同的列表格式。

(我是WinSCP的作者)