Click here to Skip to main content
15,893,588 members
Articles / Programming Languages / C#
Article

In-place file regex replacement

Rate me:
Please Sign up or sign in to vote.
2.25/5 (3 votes)
31 Jan 2008CPOL 15.4K   8  
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:

C#
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:

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --