Recusive GetFiles for DirectoryInfo via a C# Iterator
I have been working on a project using C# Express
and so I have been playing around with some of the new C# 2.0 features. In my project I had a need to get all the files of a
particular type in a given directory including all sub-directories. The DirectoryInfo class has a method GetFiles that takes a
search pattern (ie "*.exe") but it only searches that directory it doesn't search sub-directories. So I figured this would be a
good chance for me to play with these new things called iterators. At any rate I wrote a recursive version of GetFiles using an
iterator so that I could do a simple foreach loop to get all the files recursively.
public static IEnumerable<FileInfo> GetFilesRecursive(DirectoryInfo dirInfo)
{
return GetFilesRecursive(dirInfo, "*.*");
}
public static IEnumerable<FileInfo> GetFilesRecursive(DirectoryInfo dirInfo, string searchPattern)
{
foreach (DirectoryInfo di in dirInfo.GetDirectories())
foreach (FileInfo fi in GetFilesRecursive(di, searchPattern))
yield return fi;
foreach (FileInfo fi in dirInfo.GetFiles(searchPattern))
yield return fi;
}