Search and replace string recursively in C#

static void ProcessDir(string path, string search, string replace)
{
    // First access subdirectories
    string[] subDirs = Directory.GetDirectories(path);
 
    foreach (string curSubDir in subDirs)
    {
        ProcessDir(Path.Combine(path, curSubDir));
    }
 
    // Now process files
    string[] files = Directory.GetFiles(path, "*.txt");
 
    foreach(string curFile in files) {
        ProcessFile(Path.Combine(path, curFile), search, replace);
    }
}
 
private static void ProcessFile(string path, string search, string replace)
{
    StreamReader input = new StreamReader(path);
    string content = input.ReadToEnd();
    input.Close();
 
    content = Regex.Replace(content, search, replace);
 
    try
    {
        StreamWriter output = new StreamWriter(path);
        output.Write(content);
        output.Close();
    }
    catch (IOException)
    {
        Console.WriteLine("Skipping file " + path);
        return;
    }
}

Download this snippet

Searches recursively for *.txt files in a directory and subdirectories and replaces all occurences of "string search" with "string replace"

Twitter Twitter

5 Comments to “ Search and replace string recursively in C#”

  1. Anonymous  on Sep 04, 2009

    wyc3NV <a href="http://xrxqqjfaxqct.com/">xrxqqjfaxqct</a>, [url=http://emjvosxvpwcf.com/]emjvosxvpwcf[/url], [link=http://zuycrgiyvvih.com/]zuycrgiyvvih[/link], http://korriymxudcl.com/

  2. Anonymous  on Sep 25, 2009

    QxAaHK <a href="http://cuxniuktvclv.com/">cuxniuktvclv</a>, [url=http://asjrowboklqk.com/]asjrowboklqk[/url], [link=http://qzwcnbwaeirl.com/]qzwcnbwaeirl[/link], http://nvlmdvitfaig.com/

  3. Anonymous  on Jan 13, 2010

    3r4DGf <a href="http://bahxpfppwwtb.com/">bahxpfppwwtb</a>, [url=http://kdzwueflsnhm.com/]kdzwueflsnhm[/url], [link=http://qvuvosnncfud.com/]qvuvosnncfud[/link], http://znhsochpnppe.com/

  4. Anonymous  on Jan 22, 2010

    gN5ARN <a href="http://sohypzjmzjff.com/">sohypzjmzjff</a>, [url=http://okrbkkdcvbux.com/]okrbkkdcvbux[/url], [link=http://hahkhlxiwfyx.com/]hahkhlxiwfyx[/link], http://okhdfvcrgkpy.com/

  5. Anonymous  on Mar 14, 2010

    UkEyz0 <a href="http://vxbtuhhdvbqv.com/">vxbtuhhdvbqv</a>, [url=http://ehmroxiilcyp.com/]ehmroxiilcyp[/url], [link=http://zdqmqkgnayei.com/]zdqmqkgnayei[/link], http://uviyswkugspm.com/

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>