Open a file and replace strings in C#
Can be done in one line:
File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));
If you're reading large files in, and you string for replacement may not appear broken across multiple lines, I'd suggest something like the following...
private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm)
{
string tempLineValue;
using (FileStream inputStream = File.OpenRead(originalFile) )
{
using (StreamReader inputReader = new StreamReader(inputStream))
{
using (StreamWriter outputWriter = File.AppendText(outputFile))
{
while(null != (tempLineValue = inputReader.ReadLine()))
{
outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm));
}
}
}
}
}
Then you'd have to remove the original file, and rename the new one to the original name, but that's trivial - as is adding some basic error checking into the method.
Of course, if your replacement text could be across two or more lines, you'd have to do a little more work, but I'll leave that to you to figure out. :)
using System;
using System.IO;
using System.Text.RegularExpressions;
public static void ReplaceInFile(
string filePath, string searchText, string replaceText )
{
var content = string.Empty;
using (StreamReader reader = new StreamReader( filePath ))
{
content = reader.ReadToEnd();
reader.Close();
}
content = Regex.Replace( content, searchText, replaceText );
using (StreamWriter writer = new StreamWriter( filePath ))
{
writer.Write( content );
writer.Close();
}
}