Answers
This step-by-step article shows how to recursively search subdirectories for files in a C# Windows Forms application. A search string is specified so that you can find files.
Directory recursion is a common IO task. The FileSystemObject makes this job easy for Component Object Model applications. Now, these activities have become even easier in .NET. Similar to the FileSystemObject, the classes in the System.IO namespace provides an object-oriented way to access files and directories.
////// Dirs the search. /// /// The s dir. static void DirectorySearch(string sDir) { try { foreach (string d in Directory.GetDirectories(sDir)) { foreach (string f in Directory.GetFiles(d)) { Console.WriteLine(f); } DirSearch(d); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } private static void Main(string[] args) { DirectorySearch(@"c:\Cars\Class"); }
Can you call Directory.GetFiles() with multiple filters?
//For .NET 4.0 and later, var files = Directory.EnumerateFiles("c:\Cars\Class", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp4") || s.EndsWith(".png")); //For earlier versions of .NET, var files = Directory.GetFiles("c:\Cars\Class", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp4") || s.EndsWith(".png"));
Note that with .NET 4.0, you can replace Directory.GetFiles with Directory.EnumerateFiles, msdn.microsoft.com/en-us/library/dd383571.aspx, which will avoid the memory