Directories are often nested. Sometimes we need a list of files in a folder, and also those in each subdirectory.
AllDirectories
The .NET Framework allows a SearchOption.AllDirectories
argument to the Directory.GetFiles
and EnumerateFiles
methods. This is the easiest way to recursively get files.
GetFiles
This program gets a string
array of all the files at a certain level of the file system. It also covers all sublevels. Then, it loops through the result and prints the file paths.
Directory.GetFiles
is the starting path. You must escape the backslashes in Windows paths.string
, you can filter files.SearchOption.AllDirectories
, which indicates you want a recursive file search.using System; using System.IO; class Program { static void Main() { // Get list of files in the specific directory. // ... Please change the first argument. string[] files = Directory.GetFiles("C:\\PerlsComStage\\", "*.*", SearchOption.AllDirectories); // Display all the files. foreach (string file in files) { Console.WriteLine(file); } } }C:\PerlsComStage\Default.aspx C:\PerlsComStage\Global.asax C:\PerlsComStage\Web.config C:\PerlsComStage\bin\PerlsComWebProject1.dll C:\PerlsComStage\bin\PerlsComWebProject1.pdb
List
exampleWe convert the array returned by Directory.GetFiles
to a List
. Then we pass the List
instance to another method and display the value returned by its Count
property.
using System; using System.Collections.Generic; using System.IO; class Program { static void Main() { // Make sure directory exists before using this! var files = new List<string>(Directory.GetFiles("C:\\folder", "*.*", SearchOption.AllDirectories)); Method(files); } static void Method(List<string> files) { Console.WriteLine(files.Count); } }22
EnumerateFiles
This method receives the directory path as its first argument. The second two arguments are optional. To recurse through directories, use AllDirectories
.
EnumerateFiles
, we receive an IEnumerable
string
. This must be evaluated in a foreach
-loop or extension method.using System; using System.IO; class Program { static void Main() { // Call EnumerateFiles in a foreach-loop. foreach (string file in Directory.EnumerateFiles(@"c:\files", "*.*", SearchOption.AllDirectories)) { // Display file path. Console.WriteLine(file); } } }c:\files\index.html c:\files\style.css c:\files\images\logo.png c:\files\images\picture.jpg
It is possible to develop a method that uses recursion, or stack-based recursion, to scan directories. This is fun to do, and may be a good learning experience.
AllDirectories
is probably a much better choice due to its well-tested implementation.Directory.GetFiles
method can perform a recursive file listing. Instead of custom implementations, this method overload provides a clearer, simpler abstraction.