Thursday, August 8, 2013

C#: Find in Files

The following method returns the list of files in a directory and the line location within the files that contains a particular text string. it iteratively search the sub directories of the directory.

public void FindInFiles(string dir_path, Dictionary<string, Dictionary<int, string>> results, string text_to_find, string extension=null)
{
 DirectoryInfo dir = new DirectoryInfo(dir_path);
 DirectoryInfo[] sub_dirs = dir.GetDirectories();
 FileInfo[] files = dir.GetFiles();

 foreach (FileInfo file in files)
 {
  string file_path=file.FullName;
  if (!string.IsNullOrEmpty(extension) && file.Extension != extension) continue;

  using (StreamReader reader = new StreamReader(file.OpenRead()))
  {
   string line;
   int line_index=0;
   while ((line = reader.ReadLine()) != null)
   {
    line_index++;
    if (line.Contains(text_to_find))
    {
     Dictionary<int, string> found_locations = null;
     if (results.ContainsKey(file_path))
     {
      found_locations = results[file_path];
     }
     else
     {
      found_locations = new Dictionary<int, string>();
      results[file_path] = found_locations;
     }
     found_locations[line_index] = line;
    }
   }
  }
 }

 foreach (DirectoryInfo sub_dir in sub_dirs)
 {
  string sub_dir_path=sub_dir.FullName;
  FindInFiles(sub_dir_path, results, text_to_find, extension);
 }
}
The following code snippet shows how to use this method:
string dir_path="C:\temp";
string text_to_find="SimuKit.DomainModels\";
string extension=".sln";
Dictionary<string, Dictionary<int, string>> results=new Dictionary<string, Dictionary<int, string>>();

FindInFiles(dir_path, results, text_to_find, extension);
foreach (string file_path in results.Keys)
{
 Dictionary<int, string> line_content = results[file_path];
 
 foreach (int line_index in line_content.Keys)
 {
  Console.writeline("{0} appears in file {1} in line {2}, content: {3}", text_to_find, file_path, line_index, line_content[line_index]);
 }
}

No comments:

Post a Comment