FtpWebRequest ListDirectory不会返回所有文件 [英] FtpWebRequest ListDirectory does not return all files
问题描述
我试图从一个拥有大约9000个文件的FTP位置检索文件列表。
但是下面的代码总是只给出97个文件。在第98个文件的循环开始处, StreamReader.Peek()
变为-1
输出test.txt总是只有前97个文件,因为FTP响应本身只包含97个文件。
欣赏任何帮助。
requestList =(FtpWebRequest)WebRequest.Create(xxx);
requestList.Credentials = new NetworkCredential(xx,xx);
requestList.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
responseList =(FtpWebResponse)requestList.GetResponse();
responseListStream = responseList.GetResponseStream();
listReader = new StreamReader(responseListStream);
using(StreamWriter w = new StreamWriter(test.txt))
{
while(listReader.Peek()> = 0)
{
w.WriteLine(listReader.ReadLine());
}
w.Close();
Peek()
条件是错误的。它会打破你的循环,只要暂时没有数据准备好阅读。 使用此代码:
字符串行;
while(!string.IsNullOrEmpty(line = listReader.ReadLine()))
{
w.WriteLine(line);
}
虽然如果您只需复制流,请使用:
w.Write(listReader.ReadToEnd());
甚至更好(更高效):
<使用(Stream fileStream = File.Create(test.txt))
{
responseListStream.CopyTo(fileStream); pre>
}
I am trying to retrieve the list of files from a FTP location which has about 9000 files.
But the following code always gives only 97 files. In the beginning of the loop for the 98th file, the StreamReader.Peek()
turns to -1
The output "test.txt" always has only the first 97 files, as in, the FTP response itself contains only 97 files.
Appreciate any help.
requestList = (FtpWebRequest)WebRequest.Create("xxx");
requestList.Credentials = new NetworkCredential("xx", "xx");
requestList.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
responseList = (FtpWebResponse)requestList.GetResponse();
responseListStream = responseList.GetResponseStream();
listReader = new StreamReader(responseListStream);
using (StreamWriter w = new StreamWriter("test.txt"))
{
while (listReader.Peek() >= 0)
{
w.WriteLine(listReader.ReadLine());
}
w.Close();
}
The Peek()
condition is wrong. It breaks your loop whenever there's momentarily no data ready for reading.
Use this code:
string line;
while (!string.IsNullOrEmpty(line = listReader.ReadLine()))
{
w.WriteLine(line);
}
Though if you just need to copy the stream, use this:
w.Write(listReader.ReadToEnd());
Or even better (more efficient):
using (Stream fileStream = File.Create("test.txt"))
{
responseListStream.CopyTo(fileStream);
}
这篇关于FtpWebRequest ListDirectory不会返回所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!