Home > Backend Development > C++ > How Can I Retrieve Multiple File Types Using Directory.GetFiles() or EnumerateFiles()?

How Can I Retrieve Multiple File Types Using Directory.GetFiles() or EnumerateFiles()?

DDD
Release: 2025-01-26 19:21:10
Original
683 people have browsed it

How Can I Retrieve Multiple File Types Using Directory.GetFiles() or EnumerateFiles()?

Efficiently Retrieving Files of Multiple Types

The Directory.GetFiles() method, while seemingly straightforward, doesn't directly support multiple file type filters. However, several effective strategies exist to overcome this limitation.

For .NET 4.0 and later versions, the EnumerateFiles() method offers a superior solution using LINQ's Where() clause:

var files = Directory.EnumerateFiles("C:\path", "*.*", SearchOption.AllDirectories)
            .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));
Copy after login

This elegantly filters the enumerated files based on specified extensions.

For older .NET versions, a comparable approach is possible:

var files = Directory.GetFiles("C:\path", "*.*", SearchOption.AllDirectories)
            .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));
Copy after login

However, it's crucial to remember that GetFiles() returns a complete array in memory. This can lead to performance issues and high memory consumption, especially when dealing with extensive directories. Therefore, using EnumerateFiles() is strongly recommended for optimal efficiency.

The above is the detailed content of How Can I Retrieve Multiple File Types Using Directory.GetFiles() or EnumerateFiles()?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template