How to search for a specific word in multiple files

How can I find a specific word in multiple files inside a directory using C#

Below code will give me occurrence in a single file, how can I convert it so that it will search a specific word in all the files and gives me the word count?

string text = File.ReadAllText(@"D:\Temp\MyText.txt").ToLower();
int hellos = Regex.Matches(text, @"\bhello\b").Count;

Please let me know if I could do it in a simpler way using any other methods.


Solution 1:

Let's query the directory with a help of Linq:

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

...

int hellos = Directory
  .EnumerateFiles(@"D:\Temp", "*.txt")
  .Select(file => File.ReadAllText(file))
  .Select(text => Regex.Matches(text, @"\bhello\b", RegexOptions.IgnoreCase).Count)
  .Sum();

Solution 2:

Try this:

private int GetWordCountInFiles(string FolderPath, string SearchWord, string FileExtension)
    {
        int WordCount = 0;
        string[] Files = System.IO.Directory.GetFiles(FolderPath);

        for (int i = 0; i < Files.Length; i++)
        {
            string text = System.IO.File.ReadAllText(Files[i]).ToLower();
            WordCount += System.Text.RegularExpressions.Regex.Matches(text, @"\b" + SearchWord + "\b").Count;
        }
        return WordCount;
    }

And here is an example of how to use the function:

int WordCount = GetWordCountInFiles(@"F:\", "Hello", ".txt");