Find and Replace text in all files of a given folder , including subfolders with C#

If you want to find and replace some text in all files of a given folder, including subfolders, you can use the following C# code:

   string rootfolder = @"C:\Temp";
string[] files = Directory.GetFiles(rootfolder, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{    try
{    string contents = File.ReadAllText(file);
contents = contents.Replace(@"Text to find", @"Replacement text");
       // Make files writable
File.SetAttributes(file, FileAttributes.Normal);

File.WriteAllText(file, contents);
catch (Exception ex)
{    Console.WriteLine(ex.Message);


  1. Shazmeister

    Great code Roel, if i wanted to do multiple find and replace statements how would i do it i.e
    I have the following tags i need to replace with nothing

Leave a Reply

Your email address will not be published. Required fields are marked *