我想循环一个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(); } }
您应该在每个循环结束时添加某种暂停.你不想轰炸服务器.