If you’re using .NET 4, you may wish to use the System.IO.DirectoryInfo.EnumerateDirectories and System.IO.DirectoryInfo.EnumerateFiles methods. If you use the Directory.GetFiles method as other posts have recommended, the method call will not return until it has retrieved ALL the entries. This could take a long time if you are using recursion.
From the documentation:
The
EnumerateFilesandGetFilesmethods differ as follows:
- When you use
EnumerateFiles, you can start enumerating the collection ofFileInfoobjects before the whole collection is
returned.- When you use
GetFiles, you must wait for the whole array ofFileInfoobjects to be returned before you can access the array.Therefore, when you are working with many files and directories,
EnumerateFilescan be more efficient.