我必须读取一个大文本文件并使用C#逐行解析它.StreamReader对于小型文件,它可以很容易地完成,但是在处理大文件时它会出现内存异常.如何使其适应大文件?
以下代码捕获OutOfMemoryException:
using (StreamReader reader = new StreamReader(FileNameWithPath))
{
while ((line = reader.ReadLine()) != null)
{
// Do something here...
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 10
这几乎是懒惰线阅读器的标准代码,OutOfMemoryException除非有一些非常大的单行,否则不应该引起它.你也可以尝试:
foreach(var line in File.ReadLines(FileNameWithPath)) {
// Do something here...
}
Run Code Online (Sandbox Code Playgroud)
它只是使它更干净,但做同样的事情.所以有两种选择:
我希望后者更有可能.