loading...

Dotnet Core console App to search file contents for a phrase

anilkhandei profile image Anil Kumar Khandei ・2 min read

I guess everyone must have faced this problem of searching for file contents in windows and waiting for really really long...also at times searching network folders with thousands of files is not that convenient either.

Well I created this console app using dotnet core that you can run against any folder network or local and search for any files with specific text content.

I used the following restrictions-

1- ability to search for specific file extensions like .xml or .txt etc.
2- ability to search against files from a specific date

Add the following depedencies-

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

the input to the console application is in the below format-

dotnet SearchFilesWithContent.dll "\\networkpath\c$\myfolder\subfolder" ".xml" "date_to_look_for" "text_content_to_search"

capture the command line parameters from the args like so-

var dirPath = args[0];
var fileExtension = args[1];
var searchDate = args[2];
var searchText = args[3];

next step is to create an instance of the DirectoryInfo class using the folder path from the arguments. The DirectoryInfo class exposes a lot of useful methods and worth going through from the microsoft documentation or directly from the metadata in visual studio.

DirectoryInfo dir = new DirectoryInfo(dirPath);

We want to iterate the list of files in the folder by applying the filter on the filename and also get a collection of files so we can search for the file contents. We can do everything using a single line of code like so(we are using lambda expression using linq)-

IEnumerable<FileInfo> filelist = dir.GetFiles(fileExtension, SearchOption.AllDirectories)
                    .Where(file => file.LastWriteTime.ToString("yyyy-MM-dd")==searchDate);
        // Parameters:
        //   searchPattern:
        //     The search string to match against the names of files. This parameter can contain
        //     a combination of valid literal path and wildcard (* and ?) characters, but it
        //     doesn&#39;t support regular expressions.
        //
        //   searchOption:
        //     One of the enumeration values that specifies whether the search operation should
        //     include only the current directory or all subdirectories.
        //
        // Returns:
        //     An array of type System.IO.FileInfo.

Now we can iterate the file list to search for the specific content-

var foundFilesCtr = 0;
foreach (var item in filelist)
   if (File.ReadAllLines(item.FullName).Contains(searchText))
   {
      Console.WriteLine($"File with selected content:{item.FullName}");
      foundFilesCtr++;
   }
Console.WriteLine($"Found {foundFilesCtr} files with text {searchText}");
Console.WriteLine("------------------------------------");
Console.ReadKey();

The full program looks something like this-

static void Main(string[] args)
        {
            try
            {
                var dirPath = args[0];
                var fileExtension = args[1];
                var searchDate = args[2];
                var searchText = args[3];
                DirectoryInfo dir = new DirectoryInfo(dirPath);

                IEnumerable<FileInfo> filelist = dir.GetFiles(fileExtension, SearchOption.AllDirectories)
                    .Where(file => file.LastWriteTime.ToString("yyyy-MM-dd")==searchDate);

                var foundFilesCtr = 0;
                Console.WriteLine($"Searching for {searchText} in {dir}");
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Search results...");
                Console.WriteLine($"Found {filelist.Count()} files with extenstion {fileExtension} and dated {searchDate}");
                foreach (var item in filelist)
                    if (File.ReadAllLines(item.FullName).Contains(searchText))
                    {
                        Console.WriteLine($"File with selected content:{item.FullName}");
                        foundFilesCtr++;
                    }
                Console.WriteLine($"Found {foundFilesCtr} files with text {searchText}");
                Console.WriteLine("------------------------------------");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }
            Console.ReadKey();
        }

Discussion

pic
Editor guide