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:

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

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

Leave a Reply