Recursively searching directories to find text within files in C#

A straightforward utility to recursively search for text contained within files and directories.

I created a C# console application.

The actual recursive routine to search the directories and subdirectories recursively is quite straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
foreach (var directory in Directory.GetDirectories(sDir))
{
    foreach (var filename in Directory.GetFiles(directory))
    {
        using (var streamReader = new StreamReader(filename))
        {
            var contents = streamReader.ReadToEnd().ToLower();
 
            if (contents.Contains(SearchText))
            {
                FilesFound.Add(filename);
            }
        }                       
    }
 
    DirSearch(directory);
}

Each directory is recursively searches as well as all the files contained within it.

Full code listing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace RecursiveSearch
{
    internal class Program
    {
        private static List<string> FilesFound { get; } = new List<string>();
        private const string SearchText = "get; set;";
 
        private static void DirSearch(string sDir)
        {
            try
            {
                foreach (var directory in Directory.GetDirectories(sDir))
                {
                    foreach (var filename in Directory.GetFiles(directory))
                    {
                        using (var streamReader = new StreamReader(filename))
                        {
                            var contents = streamReader.ReadToEnd().ToLower();
 
                            if (contents.Contains(SearchText))
                            {
                                FilesFound.Add(filename);
                            }
                        }                       
                    }
 
                    DirSearch(directory);
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
        private static void Main(string[] args)
        {
            DirSearch(@"E:\CodeSamples\Archive");
 
            Console.WriteLine("Files containing the word " + SearchText);
            Console.WriteLine();
 
            foreach (var file in FilesFound)
            {
                Console.WriteLine(file);
            }
 
        }
    }
}

So to search for all files containing the text “get; set” within the directory “E:\CodeSamples\Archive” gives the following output:

recursivesearch