How to loop through all the files in a directory in c .net?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Looping through files is a routine task in .NET applications that import data, clean directories, generate reports, or process media. The main design choice is whether you want a full list of files up front or a streaming iterator that starts yielding results immediately. In most real programs, Directory.EnumerateFiles is the safer default because it handles large folders better than Directory.GetFiles.
Choose the Right Enumeration API
The simplest API is Directory.GetFiles, which returns a full array of file paths:
This is fine for small folders, but it builds the complete list before your loop starts. That means higher memory usage and slower time to first result if the directory is large.
For scalable traversal, prefer Directory.EnumerateFiles:
This version streams file names lazily, which is usually what you want in batch jobs and CLI tools.
Add Patterns and Recursive Search
Real file processing rarely wants every file. Usually you want a subset such as .csv or .json, and often you want subdirectories too.
If you need several extensions, enumerate broadly and filter in code:
That approach is clear and keeps extension handling explicit.
Handle Errors Without Killing the Whole Job
The happy path is easy. The real work is surviving invalid paths, permission issues, and locked files. If your program scans a large tree, one bad folder should not necessarily stop the entire run.
This split between scan-level and file-level exceptions makes long-running jobs much more resilient.
Use DirectoryInfo When Metadata Matters
If you need file sizes or timestamps, DirectoryInfo and FileInfo can make the code cleaner:
This is useful when traversal and metadata reporting are part of the same workflow. If you only need path strings, Directory.EnumerateFiles is still simpler.
Add Async Processing Carefully
Enumeration itself is synchronous, but file processing can be asynchronous. The main trap is launching too many tasks at once. Use throttling if there are many files.
That pattern keeps throughput reasonable without opening hundreds of files at once.
Common Pitfalls
- Using
GetFileson very large directories and paying unnecessary memory cost before processing starts. - Recursing through subdirectories without handling permission failures.
- Filtering extensions with case-sensitive checks and silently skipping valid files.
- Starting unbounded asynchronous file work and exhausting handles or disk throughput.
- Hardcoding path separators instead of relying on
Pathhelpers for cross-platform code.
Summary
- '
Directory.EnumerateFilesis usually the best default for looping through files in .NET.' - Add search patterns and
SearchOption.AllDirectoriesonly when the job actually needs them. - Separate traversal errors from per-file processing errors.
- Use
DirectoryInfowhen file metadata is part of the task. - If processing is asynchronous, throttle it so enumeration stays efficient and predictable.
Related reading
- How to make an efficient solver for Puzzle Number 9
- How to map hashfunction output to bloomfilter indices?
- How to master in-place array modification algorithms?
- How to match a tree against a large set of patterns?
- How to make a .NET Windows Service start right after the installation?
- How to make a window always stay on top in .Net?
- How to match and highlight all terms in any order from an array of strings?
- how to measure running time of algorithms in python

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.