This post will discuss how to list all files in a directory in C#.

1. Using Directory.GetFiles() method

You can use the Directory.GetFiles() method to get the list of files in the specified directory. It takes the relative or absolute path of the directory to search, and returns a string array containing the file names (including their paths) in the specified directory, in no fixed order.

Download Code

 
The Directory.GetFiles() method is overloaded to accept the search pattern to match against the files in the specified directory. For example, the following code will list out all the files in the specified directory with the .jpg extension.

Download Code

 
By default, the Directory.GetFiles() method performs the search only in the current directory. To extend the search operation to include all its subdirectories, you can provide the SearchOption.AllDirectories option as the third parameter. For example, the following code will list all the files present in the specified directory and all its subdirectories with any extension (asterisk (*) matches with any file type).

Download Code

 
If you need to get the names of all files along with all the names of all its subdirectories, consider using the Directory.GetFileSystemEntries method instead. For example, the following code will recursively list out all the files and subdirectories present in the specified directory with any extension.

Download Code

2. Using DirectoryInfo.GetFiles() method

Alternatively, you can use the DirectoryInfo.GetFiles() method to return a list of files in the current directory. Here’s a working code:

Download Code

 
Like The Directory.GetFiles(), the DirectoryInfo.GetFiles() method is overloaded to accept the search pattern. The following example will return all the files in the specified directory with the .png extension.

Download Code

 
You can extend the search operation to all subdirectories by specifying the SearchOption.AllDirectories option. The following code will list all the files in the specified directory and all its subdirectories.

Download Code

3. Custom Routine

Finally, you can even write your custom routine to extend the search to include all subdirectories of the source directory, without having to use the SearchOption.AllDirectories option in the Directory.GetFiles() method. The idea is to iterate over files in the current directory and process them. If the directory contains any subdirectories, do this recursively.

Download Code

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