Efficient way to delete a line from a text file (C#)

Posted by Valentin Vasilyev on Stack Overflow See other posts from Stack Overflow or by Valentin Vasilyev
Published on 2009-02-10T13:01:55Z Indexed on 2010/05/05 18:58 UTC
Read the original article Hit count: 231

Filed under:
|
|

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);
            }
        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about file-io