6 Comments

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

6 Replies to “Find and Replace text in all files of a given folder , including subfolders with C#”

  1. 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

  2. Hi,

    I need to do more than 1 replace…how can I do that ? I tried to add more replace commands but it is not working.

    Thank you

  3. Hi, thank you for this awesome code….it works and solves the issue…but i am using this for replacing the text for classic asp and after i run the code i am facing encoding issue…can you suggest?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts