I would like to modify the following code to work with large files.
public static void Replace(string filePath, string searchText, string replaceText)
{
StreamReader reader = new StreamReader(filePath);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, searchText, replaceText);
StreamWriter writer = new StreamWriter(filePath);
writer.Write(content);
writer.Close();
}
I’m thinking that I’m going to need to open a filestream to write to a new file name, and then delete the original file and replace it with the new one when I’m done. Does that sound about right?
Also…
I love the simplicity of this routine, that aside from the necessary file i/o lines of code there is only one line of code to process the file. However, I’m also wondering if I’m sacrificing performance for simplicity… is Regex.Replace very performant?
First: you can try
Regex with Stream(it seems be more faster and less memory requirement):or see
Mono-Project Regex. It has Regex with streaming.see this article for Regex performance:
or if using
Regexis not necessary useString.Replaceand try this one line code: