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

时间:2017-11-16 13:08:47

标签: c# .net serialization ftp ftpwebrequest

我目前正在开发.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>中吗?

非常感谢!!

1 个答案:

答案 0 :(得分:4)

使用FtpWebRequest

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

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

棘手的部分是识别子目录中的文件。使用FtpWebRequest以便携方式无法做到这一点。遗憾的是,FtpWebRequest不支持MLSD命令,这是在FTP协议中检索具有文件属性的目录列表的唯一可移植方式。另请参阅Checking if object on FTP server is file or directory

您的选择是:

  • 对文件名执行操作,该文件名对于文件肯定会失败并对目录成功(反之亦然)。即您可以尝试下载&#34;名称&#34;。如果成功,它就是一个文件,如果失败,它就是一个目录。
  • 您可能很幸运,在您的具体情况下,您可以通过文件名告诉目录中的文件(即所有文件都有扩展名,而子目录则没有)
  • 您使用长目录列表(LIST command = 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);

使用第三方库

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

例如,使用WinSCP .NET assembly,只需拨打一次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的作者)

相关问题