我想在FTP文件夹上循环以检查文件是否已到达
我做:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080");
request.Credentials = new NetworkCredential("anonymous", "");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
while(true)
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
Console.WriteLine(reader.ReadToEnd());
reader.Close();
response.Close();
}
}
但是在第二次迭代中我得到了一个例外:
无法读取流
答案 0 :(得分:4)
抱歉,我错过了,您只发出一个请求并尝试多次获得回复。请尝试以下代码:
while(true)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080");
request.Credentials = new NetworkCredential("anonymous", "");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
Console.WriteLine(reader.ReadToEnd());
reader.Close();
response.Close();
}
}
您应该在每个循环结束时添加某种暂停。你不想轰炸服务器。
答案 1 :(得分:4)
您不能将FtpWebRequest
实例重复用于多个请求。
但由于FtpWebRequest
在连接池之上工作,它实际上可以重用底层FTP连接。只要FtpWebRequest.KeepAlive
设置为默认值true
。
当KeepAlive
设置为true
时,请求完成时,基础FTP连接不会关闭。当您使用相同的URL创建FtpWebRequest
的另一个实例时,将重用该连接。
while (true)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080");
request.Credentials = new NetworkCredential("anonymous", "");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// reuse the connection (not necessary, as the true is the default)
request.KeepAlive = true;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
Console.WriteLine(reader.ReadToEnd());
reader.Close();
response.Close();
}
}