我试图从一个拥有大约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());甚至更好(更高效): }
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不会返回所有文件
发布评论