我正在努力处理我目前正在撰写的一小段代码。应用程序应该每天运行一次并从ftp服务器下载所有文件。我的问题是:
虽然理论上列出direcoty内容的例程运行正常,但检查所有文件并将它们保存到列表中,实际上有2个错误:
string localPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
List<string> FtpListing = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Properties.Settings.Default.FtpUrl);
//request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
request.Credentials = new NetworkCredential(Properties.Settings.Default.FtpUsername, Properties.Settings.Default.FtpPassword);
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream()))
{
string fileName = streamReader.ReadLine();
while (fileName != null)
{
FtpListing.Add(fileName);
fileName = streamReader.ReadLine();
}
}
没有代理,它返回html,取消注释代理语句,我收到The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
错误。
我在哪里失败?
/编辑: 这是列表的屏幕截图,其中应列出所有文件,但保存完整的html文件:
答案 0 :(得分:0)
我使用HtmlAgilityPack找到了一个有效的解决方案。
由于我无法更改html回复,因此我将List<string> FtpListing
更改为简单的string
。
使用此字符串,我解析了webrequest提供的html代码中的每个<a>
标记。
代码:
string HtmlResult = String.Empty;
Console.WriteLine("Starting listing of files....");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Properties.Settings.Default.FtpUrl);
request.Credentials = new NetworkCredential(Properties.Settings.Default.FtpUsername, Properties.Settings.Default.FtpPassword);
request.UsePassive = false;
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (Stream responsestream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responsestream))
{
string _line = reader.ReadLine();
while (_line != null && _line != String.Empty)
{
HtmlResult += _line;
_line = reader.ReadLine();
}
}
}
//parse html output
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HtmlResult);
foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))
{
if(node.InnerText.Contains(".txt")) FtpListing.Add(node.InnerText);
}
Console.WriteLine("{0} Files found", FtpListing.Count);
答案 1 :(得分:0)
使用此代码返回某个ftp deirectory中的文件名列表
System.Net.FtpWebRequest ftpRequest = System.Net.FtpWebRequest)System.Net.WebRequest.Create(SourceDirectory);
ftpRequest.Credentials = new System.Net.NetworkCredential(SourceFTPUserName, SourceFTPPassword);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftpRequest.GetResponse();
System.IO.StreamReader streamReader = new System.IO.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();
return directories;
希望它有所帮助。