Home > Backend Development > C++ > How Can I Efficiently Use Directory.GetFiles() to Retrieve Multiple File Types?

How Can I Efficiently Use Directory.GetFiles() to Retrieve Multiple File Types?

Barbara Streisand
Release: 2025-01-26 19:11:09
Original
811 people have browsed it

How Can I Efficiently Use Directory.GetFiles() to Retrieve Multiple File Types?

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>
Copy after login

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>
Copy after login

This loads all files initially, then applies the same LINQ filter.

Important Notes

  • Performance: While convenient, 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.
  • Path Syntax: Always enclose your directory path in double quotes ("C:path") to avoid errors.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template