MSDN listing for recursive file search is incorrect.

The MSDN listing for how to recursively search files is incorrect. Their code (in C#, but it applies to all languages) is below. [This is for Directory.GetDirectories and Directory.GetFiles method only]

void DirSearch(string sDir)
{
	try
	{
	   foreach (string d in Directory.GetDirectories(sDir))
	   {
		foreach (string f in Directory.GetFiles(d, txtFile.Text))
		{
		   lstFilesFound.Items.Add(f);
		}
		DirSearch(d);
	   }
	}
	catch (System.Exception excpt)
	{
		Console.WriteLine(excpt.Message);
	}
}

The problem with this code may not be obvious, but if you look careful it takes in a directory, looks in that directory for sub-directories and then spits out the files in each sub-directory. It completely skips all of the files in the root search directory. While building my up-coming sync program I needed to find all files and realized quickly I was missing a large portion. That’s what I get for using MSDN examples instead of writing all the small, seemingly-obvious, subroutines myself. The preferred fix to this (written by yours truly) is as follows:

void DirSearch(string sDir)
{
   try
    {
     foreach (string f in Directory.GetFiles(sDir, txtFile.Text))
     {
       lstFilesFound.Items.Add(f);
     }
     foreach (string d in Directory.GetDirectories(sDir))
     {
       DirSearch(d);
     }
    }
   catch (System.Exception excpt)
    {
      Console.WriteLine(excpt.Message);
    }
}

It is only ever so slightly modified, but will now search in the root directory first, before recursively calling all the sub-directories. Hope this helps someone out there who can’t quite figure out what’s going wrong. Again, this should be applied to all .Net languages, not just C#. If I helped, feel free to drop me a line. I have suggested the updated version to the MSDN gods, we will see if they heed my advice.

Leave a Reply

Your email address will not be published. Required fields are marked *