This post will discuss how to recursively list all files in a directory and all its subdirectories in C#.

1. Using GetFiles and GetDirectories methods

To get the list of full names of files and subdirectories in the specified directory, we can use GetFiles and GetDirectories() methods in the System.IO.Directory class, as shown below:

Download Code

 
The above-mentioned methods are overloaded to accept the search pattern and search options. If the search pattern is specified, the method matches the pattern against the names of files and directories in the path. The search options specify whether the search should include all subdirectories or only the root directory.

The following code uses the * pattern and SearchOption.AllDirectories option to retrieve all types of files in the current directory and its subdirectories.

Download Code

2. Using EnumerateFiles and EnumerateDirectories methods

Alternatively, we can use EnumerateFiles and EnumerateDirectories to get an enumerable collection of full names of files and subdirectories in the specified directory.

The following example shows how to retrieve all files in a directory and its subdirectories.

Download Code

3. Using Directory.GetFileSystemEntries() method

Another idea is to use the Directory.GetFileSystemEntries() method returns the names of all files and subdirectories in the specified path. It is overloaded to accept search patterns and search options. If a search pattern is specified, the method matches the pattern against the names of files and directories in the path. If the SearchOption.AllDirectories option is specified, it searches inside all subdirectories.

Download Code

That’s all about listing all files in a directory and subdirectories with C#.