Summary: in this tutorial, you’ll learn how to list a directory in C# using the
method.Directory.EnumerateDirectories()
Introduction to the C# Directory.EnumerateDirectories() method
The
method returns an enumerable collection (Directory.EnumerateDirectories()
IEnumerable<string>
) of directory names that match a specified search pattern.
Here’s the syntax of the
method:Directory.EnumerateDirectories()
public static IEnumerable<string> EnumerateDirectories(
string path,
string searchPattern,
SearchOption searchOption
);
Code language: C# (cs)
In this syntax:
- The
path
specifies the path of the directory to search for subdirectories. - The
searchPattern
specifies a search pattern. - The
searchOption
instructs the method to search only the current directory (SearchOption.TopDirectoryOnly
) or include all subdirectories (SearchOptioin.AllDirectories
).
The search pattern can contain wildcards like *
and ?
:
- Asterisk (
*
) – matches zero or more characters. - Question mark (
?
) – matches exactly one character.
For example:
backup*
matches a string that starts with backup and is followed by zero or more characters e..g,backup2023
,backupABC
.backup?
matches a string that starts with backup and is followed by a character e.g.,backup1
,backup2
.
Besides invalid characters, the search pattern cannot end with two periods (..
) or contain two periods (..
)
Note that the searchPattern
doesn’t support regular expressions.
C# listing directory example
The following program demonstrates how to find the directories whose names start with "0"
in the C:\backup
directory:
using static System.Console;
string path = @"C:\backup\2023";
var dirnames = Directory.EnumerateDirectories(
path,
"0*",
SearchOption.AllDirectories
);
foreach (var dirname in dirnames)
{
WriteLine(dirname);
}
Code language: C# (cs)
Suppose the C:\backup
directory is like this:
c:\backup
└── 2023
├── 01
| └── readme.txt
├── 02
├── 03
├── 04
├── 05
├── 06
├── 07
├── 08
├── 09
├── 10
├── 11
└── 12
directory: 13 file: 1
Code language: plaintext (plaintext)
The program will show the following output:
C:\backup\2023\01
C:\backup\2023\02
C:\backup\2023\03
C:\backup\2023\04
C:\backup\2023\05
C:\backup\2023\06
C:\backup\2023\07
C:\backup\2023\08
C:\backup\2023\09
Code language: plaintext (plaintext)
Summary
- Use C#
method to return anDirectory.EnumerateDirectories()
IEnumerable<string>
of paths to directories that match specified criteria.