Stew C
Stew C

Reputation: 758

Read file line by line and do regex replace

I've written a program that reads a text file into a variable, does a regex replace on the text, and writes it back to the file. Obviously this is not scalable for large text files; I want to be able to read the text file line-by-line and do a regex replace for a desired pattern.

Here is my non-scalable code:

static void Main(string[] args) {
    var fileContents = System.IO.File.ReadAllText("names.txt");
    string pattern = "Ali";
    string rep = "Tyson";

    Regex rgx = new Regex(pattern);
    fileContents = rgx.Replace(fileContents, rep);

    System.IO.File.WriteAllText("names.txt", fileContents);}

I know how to use StreamReader for reading a file line-by-line but when I tried nest StreamWriter inside of StreamReader so I could write to the file while searching line-by-line I ran into an unhandled exception error.

Does anyone know how to solve this?

Upvotes: 4

Views: 2588

Answers (1)

Kurubaran
Kurubaran

Reputation: 8902

You could try this,

using (var input = File.OpenText("input.txt"))
using (var output = new StreamWriter("output.txt")) {
  string line;
  while (null != (line = input.ReadLine()) {
     // Apply regex to line before writing to new outpu file
     output.WriteLine(line);
  }
}

Once you finish reading and writing all lines to output.txt you could replace input.txt with output.txt.

Upvotes: 2

Related Questions