65.9K
CodeProject is changing. Read more.
Home

In-place file regex replacement

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.25/5 (3 votes)

Jan 31, 2008

CPOL
viewsIcon

15503

A function to apply a regex replacement to a file.

Introduction

This is a basic function for editing a file in-place, applying a Regex and a replacement string to each line.

Using the code

Here's the code:

using System.Text.RegularExpressions;

public static void ApplyRegexToFile(string filename,
        Regex match, string replacement)
{
    string temp = Path.GetTempFileName();
    using (StreamReader sr =
        new StreamReader(File.Open(filename, FileMode.Open)))
    using (StreamWriter sw =
        new StreamWriter(File.Open(temp, FileMode.Append)))
    {
        string line;
        while ((line = sr.ReadLine()) != null) {
            line = match.Replace(line, replacement);
            sw.WriteLine(line);
        }
    }
    File.Delete(filename);
    File.Move(temp, filename);
}

Here's an example of how it might be used:

ApplyRegexToFile(@"c:\Program Files\SomeProgram\SomeConfigFile",
                 new Regex(@"(someconfigsetting)=([a-z]*)", RegexOptions.IgnoreCase),
                 "$1=newsettingvalue");