我需要从头到尾读取一个流两次。
但是以下代码会抛出 ObjectDisposedException: Cannot access a closed file
异常。
string fileToReadPath = @"<path here>";
using (FileStream fs = new FileStream(fileToReadPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
fs.Seek(0, SeekOrigin.Begin); // ObjectDisposedException thrown.
using (StreamReader reader = new StreamReader(fs))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
为什么会发生这种情况?真正被处理的是什么?同时,为何操纵 StreamReader
会以此影响关联流?难道可以期望可寻址流被多个StreamReader
读取多次吗?