Efficient way to delete a line from a text file

The most straight forward way of doing this is probably the best, write the entire file out to a new file, writing all lines except the one(s) you don’t want.

Alternatively, open the file for random access.

Read to the point where you want to “delete” the line.
Skip past the line to delete, and read that number of bytes (including CR + LF – if necessary), write that number of bytes over the deleted line, advance both locations by that count of bytes and repeat until end of file.

Hope this helps.

EDIT – Now that I can see your code

if (!_deletedLines.Contains(counter)) 
{                            
    writer.WriteLine(reader.ReadLine());                        
}

Will not work, if its the line you don’t want, you still want to read it, just not write it. The above code will neither read it or write it. The new file will be exactly the same as the old.

You want something like

string line = reader.ReadLine();
if (!_deletedLines.Contains(counter)) 
{                            
    writer.WriteLine(line);                        
}

Leave a Comment