0
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUrl);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        var response = (FtpWebResponse)request.GetResponse();
        Stream rStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(rStream);
        string fileNames = reader.ReadToEnd();
        List<string> ls = fileNames.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
        for (int i = 0; i < ls.Count; i++)
            Console.WriteLine(ls[i]);

此方法仅列出指定serverUrl目录中存在的文件。我想列出 FTP 服务器的所有文件。谁能建议我什么?

4

1 回答 1

0

我已经在 msdn 论坛中编写了相关代码,例如:下载文件夹中的每个文件

您可以使用 FtplistFile 方法获取 ftp 服务器中所有文件的列表。

这是我修改的代码示例。

private void button1_Click(object sender, EventArgs e)
    {
        string uri = "ftp://xxx.x.xx.x/";
        string username = "USERNAME";
        string password = "PASSWORD";
        ListFtpDirectory(uri, new NetworkCredential(username, password));

    }

    static void ListFtpDirectory(string url, NetworkCredential credentials)
    {
        WebRequest listRequest = WebRequest.Create(url);
        listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        listRequest.Credentials = credentials;

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

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

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

            if (permissions == "<DIR>")
            {
                Console.WriteLine($"Directory {name}");
                string fileUrl = url + name;
                ListFtpDirectory(fileUrl + "/", credentials);
            }
            else
            {
                Console.WriteLine(url+name);
                Console.WriteLine($"File {name}");
            }
        }
    }

获取文件名:

在此处输入图像描述

在 ftp 中获取文件路径:

在此处输入图像描述

于 2020-11-25T01:57:23.083 回答