C#中的Streams问题

时间:2011-12-24 10:15:20

标签: c# .net

我有这个代码用于c#读取TestFile.txt中的所有行但是当我读完时我想再次读取它然后把它放在一个字符串数组(不是List)中但是当我尝试再做它时说该文件已被使用。我想重置流或执行类似sr.Close()的操作,因为我第一次读它时想要计算Testfile.txt中有多少行。

using (StreamReader sr = new StreamReader("TestFile.txt"))
{
           string line;
           while ((line = sr.ReadLine()) != null)
           {
                     Console.WriteLine(line);
           }
}

我已经尝试在while循环之后放置if(line == null)sr.Close()但它不起作用。

2 个答案:

答案 0 :(得分:9)

为什么不将它读入List<string>然后从中构建一个数组呢?或者更简单地说,只需致电File.ReadAllLines

string[] lines = File.ReadAllLines("TestFile.txt");

虽然你可以重置底层流并刷新阅读器中的缓冲区,但我不会这样做 - 我只是以一种不需要你的方式阅读它知道前面的大小。

(事实上,我尝试使用List<string>代替string[] - 它们通常使用起来更愉快。请阅读Eric Lippert's blog post on the subject以获取更多信息。)< / p>

答案 1 :(得分:4)

您可以将BaseStream Position属性设置为0。

如果你不能(例子是HttpWebResponse流)那么一个好的选择是将流复制到MemoryStream ...你可以将Position设置为0并重新启动Stream尽可能多

Stream s = new MemoryStream();
StreamReader sr = new StreamReader(s);
// later... after we read stuff
s.Position = 0;