C# programming tip: easily find specific files from a folder, including subfolders using Directory.EnumerateFiles in .NET 4.x

Posted: (EET/GMT+2)

 

Finding files of a particular type – such as image files or Excel documents – is a pretty common need. Since the original 1.0 .NET Framework version, you could have done this with the System.IO.Directory.GetFiles method, but only for a single directory at a time. Thus, you needed to implement (an often recursive) method for working through subfolders, and then finding files in each of the subfolders found.

However, each new .NET version brings new APIs, and the version 4.0 was no exception in 2010 (along with Visual Studio 2010, which happened to be a great version by the way). This .NET 4.0 version brought a new method that you might not be aware of: Directory.EnumerateFiles.

This method can do everything the GetFiles method can, but also contains a nice option to search for subfolders, too. This is given as the third parameter like this:

IEnumerable imageFiles = Directory.EnumerateFiles(
  @"C:\MyImages", "*.jpg", SearchOption.AllDirectories);

The method returns an enumerable of the files found, along with their full pathnames.

Happy hacking!