Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

Directory.EnumerateFiles() and friends

Reference for Directory.EnumerateFiles, EnumerateDirectories and EnumerationOptions in C#: patterns, recursion, lazy enumeration and skipping inaccessible folders.

Directory.EnumerateFiles() walks a folder and yields file paths one at a time. Its siblings EnumerateDirectories() and EnumerateFileSystemEntries() do the same for subfolders or for both. Because the result is a lazy IEnumerable<string>, you can start processing the first entries immediately and stop early, which matters for large trees. The older GetFiles() family collects everything into an array before returning.

You can filter by a simple wildcard pattern and choose whether to descend into subfolders. For finer control, pass an EnumerationOptions object: it can skip folders you cannot read, control case matching, limit the recursion depth and skip hidden or system entries.

C#
foreach (string path in Directory.EnumerateFiles(root, "*.log", SearchOption.AllDirectories))
{
    Console.WriteLine(path);
}

Try it

C# Walking a small tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# EnumerationOptions and lazy results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static IEnumerable<string> Directory.EnumerateFiles(string path);
public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern);
public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern, SearchOption searchOption);
public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions);
// Same overloads: EnumerateDirectories, EnumerateFileSystemEntries
Name Description
path The folder to read. Relative paths are resolved against the current working directory.
searchPattern A wildcard pattern for the entry name: * matches any run of characters, ? matches exactly one. Default "*". It is not a regular expression and it matches names only, never the directory part.
searchOption TopDirectoryOnly (default) or AllDirectories.
enumerationOptions An EnumerationOptions object with RecurseSubdirectories, MaxRecursionDepth, IgnoreInaccessible (default true), MatchCasing, MatchType, AttributesToSkip, ReturnSpecialDirectories and BufferSize.

Returns: a lazy IEnumerable<string> of paths. Each path is the path argument combined with the entry's relative location, so a relative input gives relative results.

Errors: DirectoryNotFoundException if the folder does not exist, ArgumentException for an invalid pattern, UnauthorizedAccessException for an unreadable root. PathTooLongException and IOException are possible during the walk.

Usage notes

  • Lazy vs. eager. Enumerate* yields entries as the disk is read; GetFiles(), GetDirectories() and GetFileSystemEntries() return a complete array. Use Enumerate* for big trees or when you stop early with First() or Take(), and Get* when you need the count or want to iterate twice.
  • Order is not guaranteed. The order depends on the file system. Call .Order() (or OrderBy) when you need stable output, as the examples do.
  • The tree can change under you. Files created or deleted while you iterate may or may not appear. Do not delete the folder you are walking from inside the loop.
  • Inaccessible folders are skipped. A new EnumerationOptions has IgnoreInaccessible = true, so folders you cannot read are silently left out of a recursive walk. Set it to false if you want the exception instead.
  • Matching rules. With the default MatchType.Simple, * and ? work the same on every platform. Case sensitivity follows the platform by default (insensitive on Windows, sensitive on Linux); MatchCasing overrides that.
  • Hidden and system entries. By default AttributesToSkip is Hidden | System, so such entries are left out; set it to 0 to include them.
  • Rich metadata. For sizes and timestamps of many files, new DirectoryInfo(path).EnumerateFiles() returns FileInfo objects, and FileSystemEnumerable<T> gives you a zero-allocation transform on the raw entry data.
  • Filtering with LINQ. For anything beyond a wildcard (size, extension lists, name rules), enumerate with "*" and filter in a Where.