Efficient way to delete a line from a text file (C#)
- by Valentin Vasilyev
Hello.
I need to delete a certain line from a text file. What is the most efficient way of doing this? File can be potentially large(over million records).
Thank you.
UPDATE:
below is the code I'm currently using, but I'm not sure if it is good.
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);
}
}