Read the file line by line and replace the regex

I wrote a program that reads a text file in a variable, whether the regular expression replaces the text and writes it back to the file. Obviously, this does not scale for large text files; I want to be able to read a text file in turn and perform a regular expression replacement for the desired pattern.

Here is my unscaled 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 to read a file in turn, but when I tried to embed StreamWriter inside StreamReader so that I could write to a file when searching in turn, I encountered an unhandled exception error.

Does anyone know how to solve this?

+4
1

,

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

output.txt, input.txt output.txt.

+1

Source: https://habr.com/ru/post/1568805/


All Articles