C# - FtpWebRequest - 通过同一连接/登录的多个请求

时间:2016-06-04 21:57:07

标签: c# .net ftp ftpwebrequest

我想在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();
    }
}

但是在第二次迭代中我得到了一个例外:

  

无法读取流

2 个答案:

答案 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();
    }
}