我有一个textReader,在一个特定的实例中,我希望能够快速地前进到文件的末尾,这样其他可能包含对此对象的引用的类将无法在不获取空值的情况下调用tr.ReadLine()。
这是一个很大的文件。我不能使用TextReader.ReadToEnd(),因为它通常会导致OutOfMemoryException
我想我应该问问社区是否有一种方法可以在不使用TextReader.ReadToEnd()的情况下查找流,它返回文件中所有数据的字符串。
当前的方法,效率低下。
下面的示例代码是一个样机。显然,我不会在打开一个文件时直接使用if语句来询问我是否要读到最后。
TextReader tr = new StreamReader("Largefile");
if(needToAdvanceToEndOfFile)
{
while(tr.ReadLine() != null) { }
}所需的解决方案(请注意,此代码块包含假的“概念”方法或由于of异常的风险而无法使用的方法)
TextReader tr = new StreamReader("Largefile");
if(needToAdvanceToEndOfFile)
{
tr.SeekToEnd(); // A method that does not return anything. This method does not exist.
// tr.ReadToEnd() not acceptable as it can lead to OutOfMemoryException error as it is very large file.
}一种可能的替代方法是使用tr.ReadBlock(args)以更大的块读取文件。
我在((StreamReader)tr).BaseStream上找了找,但找不到任何有用的东西。
因为我是这个社区的新手,所以我想我会看看是否有人能立刻知道答案。
发布于 2011-07-26 10:50:11
如果你已经读取了任何文件内容,你必须丢弃任何缓冲的数据--因为数据是缓冲的,所以即使你寻找底层的流到最终工作的例子,你也可能得到内容:
StreamReader sr = new StreamReader(fileName);
string sampleLine = sr.ReadLine();
//discard all buffered data and seek to end
sr.DiscardBufferedData();
sr.BaseStream.Seek(0, SeekOrigin.End);documentation中提到的问题是
当您调用其中一个
方法时,StreamReader类缓冲来自基础流的输入。如果在将数据读入缓冲区后操作基础流的位置,则基础流的位置可能与内部缓冲区的位置不匹配。若要重置内部缓冲区,请调用DiscardBufferedData方法
发布于 2011-07-26 10:20:42
使用
reader.BaseStream.Seek(0, SeekOrigin.End);测试:
using (StreamReader reader = new StreamReader(@"Your Large File"))
{
reader.BaseStream.Seek(0, SeekOrigin.End);
int read = reader.Read();//read will be -1 since you are at the end of the stream
}编辑:使用您的代码测试它:
using (TextReader tr = new StreamReader("C:\\test.txt"))//test.txt is a file that has data and lines
{
((StreamReader)tr).BaseStream.Seek(0, SeekOrigin.End);
string foo = tr.ReadLine();
Debug.WriteLine(foo ?? "foo is null");//foo is null
int read = tr.Read();
Debug.WriteLine(read);//-1
}https://stackoverflow.com/questions/6824514
复制相似问题