我在 C# 中工作,我有一个大文本文件 (75MB) 我想保存匹配正则表达式的行
我尝试用流阅读器和 ReadToEnd 读取文件,但它需要 400MB 的内存
再次使用时会产生内存不足异常。
然后我尝试使用 File.ReadAllLines():
string[] lines = File.ReadAllLines("file");
StringBuilder specialLines = new StringBuilder();
foreach (string line in lines)
if (match reg exp)
specialLines.append(line);
一切都很好,但是当我的函数结束时,占用的内存并没有清除,我 剩下 300MB 的已用内存,仅在调用函数和执行行时: string[] lines = File.ReadAllLines("文件"); 我看到内存减少到 50MB,然后重新分配回 200MB
我怎样才能清除这个内存或以不同的方式获得我需要的行?
最佳答案
var file = File.OpenRead("myfile.txt");
var reader = new StreamReader(file);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
//evaluate the line here.
}
reader.Dispose();
file.Dispose();
关于c# - 如何从 C# 中的文本文件中获取某些行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4451692/