How to recursively list all the files in a directory and child directories in C#?
In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list:
public static IEnumerable GetAllFiles(string path,
Func checkFile = null)
{
string mask = Path.GetFileName(path);
if (string.IsNullOrEmpty(mask)) mask = "*.*";
path = Path.GetDirectoryName(path);
string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);
foreach (string file in files)
{
if (checkFile == null || checkFile(new FileInfo(file)))
yield return file;
}
}
Use like this:
var list = GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();