FtpWebRequest ListDirectory不会返回所有文件

编程入门 行业动态 更新时间:2024-10-28 04:28:41
本文介绍了FtpWebRequest ListDirectory不会返回所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图从一个拥有大约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.ListDirectoryDe​​tails; 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不会返回所有文件

本文发布于:2023-11-05 16:06:43,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   FtpWebRequest   ListDirectory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!