-3

I tried to remove a line from text file which contains a particular word. However I need a better approach to delete the line.

Here is the code I used:

 var oldLines = System.IO.File.ReadAllLines(filepath);
            var newLines = oldLines.Where(line1 => !line1.Contains("Value"));
            System.IO.File.WriteAllLines(filepath, newLines);

By using this my task was completed, but with the following performance issues: If the file contains 10 lakhs lines it must read 10lakhs line and write 10 lakhs lines, so it takes more time.

Randhi Rupesh
  • 14,650
  • 9
  • 27
  • 46

1 Answers1

1
string line = null;
string line_to_delete = "sample line i want to delete";

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            if (String.Compare(line, line_to_delete) == 0)
                continue;   
            writer.WriteLine(line);
        }
    }
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396