【问题标题】:How to List Directory Contents with FTP in C#?如何在 C# 中使用 FTP 列出目录内容?
【发布时间】:2011-03-18 22:55:10
【问题描述】:

如何在 C# 中使用 FTP 列出目录内容?

我使用下面的代码通过 FTP 列出目录内容,它以 XML 格式返回结果,但我只想要目录的名称而不是全部内容。

我该怎么做?

public class WebRequestGetExample
{
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        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();
    }
}

MSDN

【问题讨论】:

标签: c# .net ftp directory-listing


【解决方案1】:

试试这个:

FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
ftpRequest.Credentials =new NetworkCredential("anonymous","janeDoe@contoso.com");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());

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

string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
    directories.Add(line);
    line = streamReader.ReadLine();
}

streamReader.Close();

它给了我一个目录列表...全部列在目录字符串列表中...告诉我这是否是您需要的

【讨论】:

  • 嗨,您的代码以 XML 格式返回结果我只想要远程系统目录,因为我需要将该目录名称绑定到树视图。获取 XML 对我不起作用。
  • @swapnil 我上面的代码(我编辑过的)对你有用吗?只是好奇
  • 它返回给我 proxy-1.lge.net:8080/squid-internal-static/icons/…" ALT="[DIR] "> Swapnil. . . . . . . . . . . . . Jul 21 09:43 其中“Swapnil”是目录的名称。我不希望所有其他的东西只是我必须在树视图中显示的目录的名称。我无法在树视图中显示所有这些细节。有什么建议或修改吗?
  • @Swapnil Gupta,你得到 HTML 的结果不是代码的错,而是你的 FTP 服务器的设置。
  • @mint hi mint 我试过你的代码,但我得到一个错误的对象名称:'System.Net.Sockets.NetworkStream'。
【解决方案2】:

您可能正在寻找PrintWorkingDirectory

【讨论】:

  • 当我使用 PrintWorkingDirectory 时出现错误:“使用 HTTP 代理时不支持请求的 FTP 命令” FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri); ftpRequest.Credentials = new NetworkCredential("...", "..."); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse 响应 = (FtpWebResponse)ftpRequest.GetResponse(); //错误 StreamReader streamReader = new StreamReader(response.GetResponseStream());字符串 sResult = streamReader.ReadToEnd(); streamReader.Close();
  • 尝试在您的代码中将 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory 更改为 ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkDirectory...
  • @monO : "使用 HTTP 代理时不支持请求的 FTP 命令" 。这个异常我正在上线“FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();”
【解决方案3】:

您需要列出目录内容的ListDirectory

编辑:或者你可以使用这个 Chilkat 库,它为你很好地包装了它

【讨论】:

  • ListDirectory 也以 XML 格式列出结果。我只想要远程系统目录,因为我需要将该目录名称绑定到树视图。获取 XML 对我不起作用。谢谢。
  • 是的,我浏览了 Chilkat 图书馆,但我不想使用任何第 3 方。谢谢。您还有其他建议吗?
  • 我认为它只会返回 xml,但我可能是错的。除非您可以指定 httpwebresponse 返回纯文本,否则您可能只需要将 xml 解析为文本?
【解决方案4】:

一些代理会重新格式化目录列表,因此很难可靠地解析目录列表,除非你能保证代理不会改变

【讨论】:

    【解决方案5】:

    获取 FTP 目录内容的最简单、最有效的方法:

    var contents = GetFtpDirectoryContents(new Uri("ftpDirectoryUri"), new NetworkCredential("userName", "password"));

        public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential)
        {
            var directoryContents = new List<string>(); //Create empty list to fill it later.
            //Create ftpWebRequest object with given options to get the Directory Contents. 
            var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory);
            try
            {
                using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response.
                using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream.
                {
                    var line = string.Empty; //Initial default value for line.
                    do
                    {
                        line = streamReader.ReadLine(); //Read current line of Stream.
                        directoryContents.Add(line); //Add current line to Directory Contentss List.
                    } while (!string.IsNullOrEmpty(line)); //Keep reading while the line has value.
                }
            }
            catch (Exception) { } //Do nothing incase of Exception occurred.
            return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories.
        }
    
        public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
        {
            var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
            ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.
    
            if (!string.IsNullOrEmpty(method))
                ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
            return ftpWebRequest; //Return the configured FtpWebRequest.
        }
    

    【讨论】:

      【解决方案6】:

      在下面的链接中有一个方法 GetDirectoryInformation() 从 FTP 目录中递归获取文件和目录。

      Getting files from FTP directory recursively

      【讨论】:

        【解决方案7】:

        如果你想列出 de 目录中的文件名,你必须把 (reqFTP.Proxy = null;) 在调用 (reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;) 之前。

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-01-16
          • 1970-01-01
          • 2010-09-11
          • 1970-01-01
          • 1970-01-01
          • 2011-01-19
          • 2019-01-11
          相关资源
          最近更新 更多