'System.OutOfMemoryException' 使用 ReadAllText() 方法时

'System.OutOfMemoryException' when using ReadAllText() method

我有一个包含 8,000,000 多行的制表符分隔文件,其中包含一些恶意制表符。

例如:

a->b->c->d
a->b->c->-->-->--d
a->b->c->d
a->b->c->d

我有一个纠正流氓标签(3个标签到1个标签)的方法如下:

string text = File.ReadAllText(filePath);
text = text.Replace("\t\t\t", "\t");
File.WriteAllText(filePath, text);

以上代码块产生以下错误:

An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll

如何一次只读取和写入一行以使整个文件不在内存中?

File.ReadLines给你一个懒惰的IEnumerable<string>。您可以迭代它,一次只加载一行。

不过,您需要写入与读取文件不同的文件。完成后可以delete/rename。

这是处理文件的单行代码:

File.WriteAllLines(outputFile, 
    File.ReadLines(inputFile).
    Select(t => t.Replace("\t\t\t", "\t"))
);