Friday, June 21, 2019

How to Recursively Walk the Directory Tree

I can't believe I've never written this up before. Like, I literally can't believe it. I swear I did this a long time ago. Oh, well. Whatever.

I frequently need to search all the files in a directory for a specific text value and I always end up rewriting the same code to do it. Well, no more! Here it is. It's based on a sample from Microsoft.

   1: private static void WalkDirectoryTree(DirectoryInfo root)
   2: {
   3:  FileInfo[] files = null;
   4:  DirectoryInfo[] subDirectories = null;
   5: 
   6:  try
   7:  {
   8:   files = root.GetFiles("*.*");
   9:  }
  10:  catch (UnauthorizedAccessException e)
  11:  {
  12:   Console.WriteLine(e.Message);
  13:  }
  14:  catch (DirectoryNotFoundException e)
  15:  {
  16:   Console.WriteLine(e.Message);
  17:  }
  18: 
  19:  if (files != null)
  20:  {
  21:   foreach (var file in files)
  22:   {
  23:    if (File.ReadLines(file.FullName).SkipWhile(line => !line.Contains("search string")).FirstOrDefault() != null)
  24:    {
  25:     Console.WriteLine(file.FullName);
  26:    }
  27:   }
  28: 
  29:   subDirectories = root.GetDirectories();
  30: 
  31:   foreach (var subDirectory in subDirectories)
  32:   {
  33:    WalkDirectoryTree(subDirectory);
  34:   }
  35:  }
  36: }

No comments:

Post a Comment