Open a file and replace strings in C#

I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.

Suggestions ?


Solution 1:

Can be done in one line:

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));

Solution 2:

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. :)