C#: Iterating Over Files in All Subfolders Under a Folder

This is reposted from my society president Yin Likun’s blog http://www.jackspace.cn/html/9802512250.html

// /// Find files with the specified extension under a given folder /// /// folder /// extension /// file path public static List GetFiles(DirectoryInfo directory, string pattern) { List result = new List(); if (directory.Exists || pattern.Trim() != string.Empty) { try { foreach (FileInfo info in directory.GetFiles(pattern)) { result.Add(info.FullName.ToString()); num++; } } catch { } foreach (DirectoryInfo info in directory.GetDirectories()) { GetFiles(info, pattern); } } return result; }

How to call it:

For example, List FindResult = GetFiles(@"C:","*.*"); gets all files on the C drive. You can also search only for images: List FindResult = GetFiles(@"drive-letter:a","*.jpg");