Click here to Skip to main content
13,048,406 members (112,951 online)
Click here to Skip to main content
Add your own
alternative version


8 bookmarked
Posted 30 Jan 2008

In-place file regex replacement

, 31 Jan 2008
Rate this:
Please Sign up or sign in to vote.
A function to apply a regex replacement to a file.


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);
    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),


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


About the Author

Mike McCabe
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 1 Feb 2008
Article Copyright 2008 by Mike McCabe
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid