想要使用C#(FtpWebResponse)从FTP读取文件列表,但它返回HTML
我使用以下代码从FTP站点获取文件。它在我的计算机上工作,但它只在我在另一台计算机上运行时返回HTML代码(当我通过浏览器访问FTP时,我可以看到HTML是网页的代码)。怎么了想要使用C#(FtpWebResponse)从FTP读取文件列表,但它返回HTML,c#,ftp,ftpwebrequest,C#,Ftp,Ftpwebrequest,我使用以下代码从FTP站点获取文件。它在我的计算机上工作,但它只在我在另一台计算机上运行时返回HTML代码(当我通过浏览器访问FTP时,我可以看到HTML是网页的代码)。怎么了 public String GetFilesAsString(string folder,string fileExtension) { StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try {
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;
}
可能是网络代理吗?尝试使用以下方法绕过代理:
reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
这是通过HTTP代理使用
FtpWebRequest
的结果。文件列表中有HTML标记,这些标记具有指向列表中各个文件的超链接
如果您不能绕过代理,那么在我们的例子中,可以将包含文件内容的节从封闭的
元素中刮出,加载到XmlDocument
,然后通过拉出文件列表。SelectNodes(“//A/text()”)
我发现了解决方案:默认代理意外启用
我现在必须使用配置文件专门禁用它:
事实上,这确实是一个.NET问题 FTP需要
被动模式
才能下载、上载
相反,请尝试使用:
reqFTP.UsePassive = true;
答对 了修正了托尔斯滕的回答。我使用reqFTP.Proxy=null;而不是GlobalProxySelection,因为它提示我它已经过时了。谢谢