分享

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

 印度阿三17 2019-06-22

我目前正在研究.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协议中检索具有文件属性的目录列表的唯一可移植方式.另见Checking if object on FTP server is file or directory.

你的选择是:

>对文件名执行操作,该文件名肯定会对文件失败并对目录成功(反之亦然).即你可以尝试下载“名称”.如果成功,它是一个文件,如果失败,它就是一个目录.
>您可能很幸运,在您的具体情况下,您可以通过文件名告诉目录中的文件(即所有文件都有扩展名,而子目录则没有)
>您使用长目录列表(LIST命令= ListDirectoryDe​​tails方法)并尝试解析特定于服务器的列表.许多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的作者)

来源:https://www./content-1-258451.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约