I know how to replace text in one txt file, but what if I need to change all the txt files in the target folder?

My code (editing one txt file):

 string text = File.ReadAllText("ΠŸΡƒΡ‚ΡŒ ΠΊ ΠΌΠΎΠ΅ΠΉ ΠΏΠ°ΠΏΠΊΠ΅ с txt-Ρ„Π°ΠΉΠ»Π°ΠΌΠΈ", "*.txt"); text = text.Replace("some text", "new value"); File.WriteAllText("test.txt", text); 
  • 3
    You have an error; the File.ReadAllText method File.ReadAllText not have an overload that takes two arguments of type String . - Dmitry

2 answers 2

You can use the Directory.GetFiles(String, String) method Directory.GetFiles(String, String)

 var files = Directory.GetFiles("ΠŸΡƒΡ‚ΡŒ ΠΊ ΠΌΠΎΠ΅ΠΉ ΠΏΠ°ΠΏΠΊΠ΅ с Ρ‚Ρ…Ρ‚ Ρ„Π°ΠΉΠ»Π°ΠΌΠΈ", "*.txt"); foreach (var file in files) { string text = File.ReadAllText(file); text = text.Replace("some text", "new value"); File.WriteAllText(file, text); } 

    You can make several try-catch blocks in order not to fly out with an error, and get the files using Directory.GetFiles :

     try { var txtFiles = Directory .GetFiles("C:\\path", "*.txt", SearchOption.AllDirectories) .ToList(); txtFiles.ForEach(file => { try { var oldText = File.ReadAllText(file); File.WriteAllText(file, oldText.Replace("match", "new value")); Console.WriteLine(@"ВСкст Π² Ρ„Π°ΠΉΠ»Π΅ '{0}' ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½.", file); } catch (Exception exception) { Console.WriteLine(@"Ошибка чтСния/записи Ρ„Π°ΠΉΠ»Π° '{0}' {1}", file, exception.Message); } }); } catch (Exception exception) { Console.WriteLine(@"Ошибка получСния списка Ρ„Π°ΠΉΠ»ΠΎΠ². Error: {0}", exception.Message); } 
    • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin ♦