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; } }
Searches recursively for *.txt files in a directory and subdirectories and replaces all occurences of "string search" with "string replace"
Most popular snippets