Want to use C# (FtpWebResponse) to read file list

2019-01-19 22:47发布

I use below codes to get files from a FTP site. It works in my computer, but it only return HTML codes when I run it on another computer (I can see that the HTML are codes of web page when I access FTP via browser). What's wrong?

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

enter image description here

4条回答
Evening l夕情丶
2楼-- · 2019-01-19 23:44

Could it be a web proxy interfering? Try to get around the proxy by using the following:

reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
查看更多
叼着烟拽天下
3楼-- · 2019-01-19 23:45

This is the result of using FtpWebRequest through an HTTP Proxy. The file listing gets pretty printed with HTML tags which have <A> hyperlinks to the individual files in the listing.

If you can't bypass the proxy, in our case it was possible to scrape the section with the file contents out of an enclosing <PRE> element, load it into an XmlDocument, and pull the file list out through .SelectNodes("//A/text()")

查看更多
老娘就宠你
4楼-- · 2019-01-19 23:45

FTP Requires PassiveMode to download, upload...

Instead, try to use:

reqFTP.UsePassive = true;
查看更多
Rolldiameter
5楼-- · 2019-01-19 23:48

I found the solution: the default proxy was enabled unexpectedly

I now have to disable it specifically using a config file:

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

In fact, it is really a .NET issue!

查看更多
登录 后发表回答