【问题标题】:Want to use C# (FtpWebResponse) to read file list from FTP, but it returns HTML想使用 C# (FtpWebResponse) 从 FTP 读取文件列表,但它返回 HTML
【发布时间】:2012-01-12 10:48:45
【问题描述】:

我使用以下代码从 FTP 站点获取文件。它可以在我的计算机上运行,​​但是当我在另一台计算机上运行它时它只返回 HTML 代码(当我通过浏览器访问 FTP 时,我可以看到 HTML 是网页的代码)。怎么了?

public String GetFilesAsString(string folder,string fileExtension)
{
    StringBuilder result = new StringBuilder();
    FtpWebRequest reqFTP;
    try
    {
        String ftpserver = ftp + folder+"/";

        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
        reqFTP.UsePassive = false;
        reqFTP.UseBinary = true;
        reqFTP.Credentials = new NetworkCredential(username, password);
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
        string line = "";

        while (reader.Peek()>-1)
        {
            line = reader.ReadLine();
            Console.WriteLine(line);//**********HTML was wrote out here*************
        }

        if (result.ToString().LastIndexOf('\n') >= 0)
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
        reader.Close();
        response.Close();

        return result.ToString();
    }
    catch (Exception ex)
    {
    }
    return null;
}

【问题讨论】:

    标签: c# ftp ftpwebrequest


    【解决方案1】:

    可能是网络代理干扰?尝试使用以下方法绕过代理:

    reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
    

    【讨论】:

    • 宾果游戏!修复了 Thorsten 的回答。我使用 reqFTP.Proxy = null;而不是 GlobalProxySelection,因为它提示我它已过时。谢谢!
    【解决方案2】:

    这是通过 HTTP 代理使用 FtpWebRequest 的结果。文件列表会打印出漂亮的 HTML 标签,其中包含指向列表中各个文件的<A> 超链接。

    如果您无法绕过代理,在我们的例子中,可以从封闭的 <PRE> 元素中刮取包含文件内容的部分,将其加载到 XmlDocument 中,然后通过.SelectNodes("//A/text()")

    【讨论】:

      【解决方案3】:

      我找到了解决办法:默认代理被意外启用了

      我现在必须使用配置文件专门禁用它:

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
         <system.net>
          <defaultProxy enabled="false" useDefaultCredentials="true"/>
        </system.net>
      </configuration>
      

      其实真的是.NET的问题!

      【讨论】:

        【解决方案4】:

        FTP 需要PassiveMode 才能下载、上传...

        相反,尝试使用:

        reqFTP.UsePassive = true;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-13
          • 1970-01-01
          • 2023-03-06
          • 1970-01-01
          • 2017-02-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多