[英]C# - FtpWebRequest - Multiple requests over the same connection/login
I want to loop on a FTP folder for check if a file has arrived 我想循环一个FTP文件夹,以检查文件是否已到达
I do: 我做:
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();
}
}
But at the second iteration I get an exception: 但在第二次迭代中,我得到一个例外:
The stream cannot be read
无法读取流
Sorry, I missed it, you're only issuing one request and trying to get a response multiple times. 对不起,我错过了,您只发出一个请求,并尝试多次获得响应。 Try the code below:
请尝试以下代码:
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();
}
}
You should add a pause of some sort at the end of each loop though. 您应该在每个循环结束时添加某种暂停。 You don't want to bombard the server.
你不想轰炸服务器。
You cannot reuse the FtpWebRequest
instance for multiple requests. 您不能将
FtpWebRequest
实例重用于多个请求。
But as the FtpWebRequest
works on top of a connection pool, it actually can reuse an underlying FTP connection. 但是,由于
FtpWebRequest
在连接池之上工作,它实际上可以重用底层的FTP连接。 As long as the FtpWebRequest.KeepAlive
is set to its default value of true
. 只要将
FtpWebRequest.KeepAlive
设置为其默认值true
。
When the KeepAlive
is set to true
, the underlying FTP connection is not closed, when the request finishes. 当
KeepAlive
设置为true
时,请求完成时,基础FTP连接不会关闭。 When you create another instance of the FtpWebRequest
with the same URL, the connection is reused. 当您使用相同的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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.