In C#, Directory.EnumerateDirectories() gives you the full paths of subfolders inside a folder. It returns an IEnumerable<string>, so a foreach loop receives the paths one at a time while the disk is being read.
GetDirectories() reads everything first and returns an array. Streaming helps with very large folders, because you can stop early and never hold every path in memory.
This is a static method of System.IO.Directory. Call it as Directory.EnumerateDirectories(...); there is no new Directory(). For an object that remembers one folder, see DirectoryInfo.
Syntax
The simplest call lists the direct subfolders. You can add a search pattern and a search option.
C#
string root = Path.Combine(Path.GetTempPath(), "codetofun-demo");
foreach (string dir in Directory.EnumerateDirectories(root)) {
Console.WriteLine(Path.GetFileName(dir));
}
Call
What it does
EnumerateDirectories(path)
Streams the direct subfolders of path.
EnumerateDirectories(path, "p*")
Only subfolders whose name matches. * means any letters, ? one letter.
Goes into every level below path, not only the first.
The order is not guaranteed. Sort the names before you print or compare them. These examples copy the names into a List and call Sort with StringComparer.Ordinal, so the output is the same on every machine.
Library declarations
C#
public static IEnumerable<string> EnumerateDirectories(string path);
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern);
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption);
Parameters
Parameter
Description
path
The folder to look in. It must exist.
searchPattern
Optional. A name filter such as "p*". The default is "*" (all).
searchOption
Optional. TopDirectoryOnly (default) or AllDirectories to include every level below.
Return Value
Return Value
Description
IEnumerable<string>
A lazy sequence of full paths (the path you passed plus the name). It is empty when there are no matching subfolders.
C# Examples
Example 1 — List Subfolders in Sorted Order
Create three folders, stream them, and print the sorted leaf names.
C#
using System;
using System.Collections.Generic;
using System.IO;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-enumdir-basic");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(Path.Combine(root, "photos"));
Directory.CreateDirectory(Path.Combine(root, "docs"));
Directory.CreateDirectory(Path.Combine(root, "music"));
List<string> names = new List<string>();
foreach (string dir in Directory.EnumerateDirectories(root)) {
names.Add(Path.GetFileName(dir));
}
names.Sort(StringComparer.Ordinal);
foreach (string name in names) {
Console.WriteLine(name);
}
Directory.Delete(root, true);
}
}
Output
docs
music
photos
How It Works
Full paths come back.Path.GetFileName cuts each one down to the folder name, which keeps machine-specific paths out of the output.
Collect, then sort. The names go into a List<string>. The disk can return them in any order, and Sort(StringComparer.Ordinal) makes the order fixed.
Alphabetical result.docs, music, photos is simple A to Z order.
Example 2 — Filter by Name and Search Every Level
Use the pattern p* first at the top level only, then through all levels.
C#
using System;
using System.Collections.Generic;
using System.IO;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-enumdir-pattern");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(Path.Combine(root, "photos"));
Directory.CreateDirectory(Path.Combine(root, "docs", "pictures"));
Directory.CreateDirectory(Path.Combine(root, "music", "pop"));
int topCount = 0;
foreach (string dir in Directory.EnumerateDirectories(root, "p*")) {
topCount++;
}
Console.WriteLine("Top level p*: " + topCount);
List<string> all = new List<string>();
foreach (string dir in Directory.EnumerateDirectories(root, "p*", SearchOption.AllDirectories)) {
all.Add(Path.GetFileName(dir));
}
all.Sort(StringComparer.Ordinal);
Console.WriteLine("All levels p*: " + string.Join(", ", all));
Directory.Delete(root, true);
}
}
Output
Top level p*: 1
All levels p*: photos, pictures, pop
How It Works
Three branches. The tree has photos, docs\pictures, and music\pop.
Pattern on the top level. With "p*" the call only looks at direct children, and only photos starts with p. The count is 1.
SearchOption.AllDirectories. The same pattern now also meets pictures and pop, which sit in other folders.
Example 3 — Stop Early Because the Listing Is Lazy
Use Any() for a quick yes or no, and break after two items.
C#
using System;
using System.IO;
using System.Linq;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-enumdir-lazy");
if (Directory.Exists(root)) Directory.Delete(root, true);
for (int i = 1; i <= 5; i++) {
Directory.CreateDirectory(Path.Combine(root, "d" + i));
}
Console.WriteLine(Directory.EnumerateDirectories(root).Any());
Console.WriteLine(Directory.EnumerateDirectories(Path.Combine(root, "d1")).Any());
int seen = 0;
foreach (string dir in Directory.EnumerateDirectories(root)) {
seen++;
if (seen == 2) break;
}
Console.WriteLine("Looked at " + seen + " of 5");
Directory.Delete(root, true);
}
}
Output
True
False
Looked at 2 of 5
How It Works
Five folders, none nested. The loop creates d1 to d5, and each has no subfolders of its own.
Any() is a cheap yes or no. It asks for only the first item. The root has children, so True. Folder d1 has none, so False.
break ends the work. The loop leaves after two folders, so the other three are never read. The program prints only how many were seen, because which two depends on the file system.
Frequently Asked Questions
EnumerateDirectories returns an IEnumerable<string> and reads the folder lazily while you loop. GetDirectories reads everything first and returns a string[]. Use Enumerate for big folders or when you may stop early.
Full paths. Use Path.GetFileName(path) when you only want the name.
Pass SearchOption.AllDirectories as the third argument.
No. The order depends on the file system. Copy the names into a List<string> and call Sort(StringComparer.Ordinal) for a fixed order.
You get DirectoryNotFoundException. Check with Directory.Exists first, or catch the exception.