I recently needed to get all files in a folder hierarchy, so I quickly wrote the following C# snippet:
List<string> files = FindMatchingFilesRecurse(startFolder, "*.txt");
…
public List<string> FindMatchingFilesRecurse(string folder, string filePattern)
{
List<string> fileList = new List<string>();
if (!string.IsNullOrEmpty(folder))
{
FindMatchingFilesHelper(folder, filePattern, fileList);
}
return fileList;
}
private void FindMatchingFilesHelper(string folder, string filePattern, List<string> list)
{
list.AddRange(Directory.GetFiles(folder, filePattern));
foreach (string dir in Directory.GetDirectories(folder))
{
FindMatchingFilesHelper(dir, filePattern, list);
}
}
But .NET 4.0 now contains the same functionality in a single method call (and as a bonus, it’s approximately 20-30% faster!):
List<string> files = Directory.EnumerateFiles(startFolder, "*.txt", SearchOption.AllDirectories).ToList();