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

前端之家收集整理的这篇文章主要介绍了C# – 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();
    }
}

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

The stream cannot be read

解决方法

对不起,我错过了,您只发出一个请求,并尝试多次获得响应.请尝试以下代码
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();
    }
}

您应该在每个循环结束时添加某种暂停.你不想轰炸服务器.

猜你在找的C#相关文章