Efficiently Fetching Multiple File Types Using Directory.GetFiles()
Need to retrieve files of different types from a directory efficiently? Directory.GetFiles()
is a handy tool, but it has limitations when dealing with multiple file extensions. While using "|" or ";" as delimiters in the search pattern doesn't work, there are effective workarounds.
Solutions for .NET 4.0 and Above
For optimal performance in newer .NET versions, leverage Directory.EnumerateFiles()
combined with LINQ:
<code class="language-csharp">var files = Directory.EnumerateFiles("C:\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));</code>
This approach first retrieves all files iteratively (improving performance compared to loading everything at once) and then filters the results using a lambda expression to keep only .mp3
and .jpg
files.
Workaround for Older .NET Versions
If you're working with older .NET versions, you can adapt the solution using Directory.GetFiles()
:
<code class="language-csharp">var files = Directory.GetFiles("C:\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));</code>
This loads all files initially, then applies the same LINQ filter.
Important Notes
Directory.EnumerateFiles()
might introduce a slight performance overhead in extremely large directories compared to a highly optimized custom solution. For performance-critical applications, manual iteration may be preferable.This refined approach provides a clear and efficient solution for retrieving multiple file types using Directory.GetFiles()
or its more efficient counterpart, Directory.EnumerateFiles()
, depending on your .NET framework version.
The above is the detailed content of How Can I Efficiently Use Directory.GetFiles() to Retrieve Multiple File Types?. For more information, please follow other related articles on the PHP Chinese website!