我需要从文本文件中删除某一行。最有效的方法是什么?文件可能会很大(超过百万条记录)。
更新: 以下是我目前正在使用的代码,但我不确定它是否好用。
internal void DeleteMarkedEntries() {
string tempPath=Path.GetTempFileName();
using (var reader = new StreamReader(logPath)) {
using (var writer = new StreamWriter(File.OpenWrite(tempPath))) {
int counter = 0;
while (!reader.EndOfStream) {
if (!_deletedLines.Contains(counter)) {
writer.WriteLine(reader.ReadLine());
}
++counter;
}
}
}
if (File.Exists(tempPath)) {
File.Delete(logPath);
File.Move(tempPath, logPath);
}
}