GetFiles with multiple extensions
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
When you need to collect files with multiple extensions in C#, a naive approach often causes duplicate paths, unnecessary disk scans, or brittle filtering logic. This usually happens when developers call Directory.GetFiles repeatedly (for example once for *.csv and once for *.txt) and then concatenate results without deduplication, normalization, or recursion controls. The issue becomes more visible in large directories, network shares, or pipelines where file order and uniqueness matter.
A robust implementation should answer a few questions clearly: Which extensions are allowed? Should search be recursive? Should extension matching be case-insensitive? Should symbolic links or hidden folders be skipped? And most importantly, how do we avoid duplicates when multiple patterns can match the same file path? This guide covers an efficient pattern that scales well and produces deterministic output.
Core Sections
1. Why duplicates happen and how to avoid them
Multiple calls to GetFiles can overlap, especially when extensions are provided in mixed forms such as .TXT, txt, and *.txt, or when your logic appends fallback wildcard searches. The fix is simple: normalize extensions first, enumerate once where possible, and use HashSet<string> with a case-insensitive comparer.
This performs one enumeration pass and guarantees unique results, even if extensions are repeated in the input.
2. Prefer EnumerateFiles over GetFiles for large trees
GetFiles materializes all matches before returning. For large directories, this can spike memory and delay the first usable result. EnumerateFiles streams items lazily, which is better for responsiveness and memory footprint.
If you need cancellation or time limits, you can wrap enumeration in your own loop and stop early based on application criteria.
3. Handle permission and path edge cases safely
Production directory scans often hit unauthorized folders, long paths, or transient IO issues. A resilient implementation traverses directories manually and catches exceptions per directory so one bad subtree does not fail the entire operation.
You can combine this with extension filtering for robust behavior in mixed-permission environments.
Common Pitfalls
- Using
GetFilesonce per extension and concatenating lists without deduplication, which leads to repeated file paths. - Comparing extensions with case-sensitive logic on systems where users expect
.TXTand.txtto be treated the same. - Accepting raw extension input (
txt,.txt,*.txt) without normalization, causing missed or duplicated matches. - Assuming recursive scans always succeed; permission-denied directories can throw and stop the whole operation if uncaught.
- Returning unsorted results and then depending on implicit order, which causes nondeterministic behavior across machines.
Summary
To retrieve files by multiple extensions without duplicates, normalize extension inputs, stream files with EnumerateFiles, and store matches in a case-insensitive HashSet. This approach is faster, more memory-efficient, and easier to reason about than repeated wildcard scans. For production use, add per-directory exception handling and deterministic ordering before returning results. With those safeguards in place, your file discovery pipeline becomes reliable even on large or imperfect directory trees.
Related reading
- GetHashCode Guidelines in C
- GetPathsOfAllDirectoriesAbove cannot be evaluated after updating .Net Framework version 4.6.2 to 4.7.2
- GetProperties to return all properties for an interface inheritance hierarchy
- Getter and Setter declaration in .NET
- Getting a 2nd IAsyncEnumerator from the same IAsyncEnumerable based on Task.WhenEach method
- Getting all types in a namespace via reflection
- Getting assembly name
- Getting current directory in .NET web application

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.