I'm trying to replace specific strings in several files. These files are read from a specific source. What I want is to read these files line by line, find my desired strings in each line and replace them by other strings.
So far I've come up with this. This is working but the problem with the below code is that it is very very slow.
I've come to the conclusion that it is because of the way I'm doing it by loading all the text in memory and writing it all at once. Now how can I do this line by line?
static void Main()
{
const string dir_source = "d:\\myfiles";
var files = Directory.GetFiles(dir_source, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
var extension = Path.GetExtension(file);
var str_old = "Google";
var str_new = "Alphabet";
if (extension == ".cs" || extension == ".xaml")
{
File.WriteAllText(file,
File.ReadAllText(file)
.Replace(str_old , str_new));
}
}
Console.WriteLine("Completed");
Console.ReadKey();
}
This SO question is doing something similar to what you want to do and is operating on a line by line basis.
The accepted answer uses this method for the file line level replace:
In addition, you may want to consider using Parallel.ForEach instead of ForEach to operate on multiple threads to help your performance.