You want to acquire a list of all the files in a certain folder, and also all the files in each subdirectory, from the operating system, using the C# programming language. Although complex methods exist that use recursion or other implementations, the .NET Framework provides the SearchOption.AllDirectories enum argument to the Directory.GetFiles method, and this offloads the complexity to the framework designers at Microsoft. In this article, then, we demonstrate the Directory.GetFiles method with these arguments.
In this first example, use propose a program that contains the Main entry point, and in the entry point, it gets a list of all the files at a certain level of the file system, and also all sublevels. Then, it loops through the result and prints the file paths. You can see that the first level files in the specified directory are printed, and then all subdirectory files as well.
--- Program that lists files recursively (C#) ---
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);
}
}
}
--- Output of the program ---
C:\PerlsComStage\Default.aspx
C:\PerlsComStage\Global.asax
C:\PerlsComStage\Web.config
C:\PerlsComStage\bin\PerlsComWebProject1.dll
C:\PerlsComStage\bin\PerlsComWebProject1.pdbUsing Directory.GetFiles method arguments. The first argument to the Directory.GetFiles method is the starting path; you must escape the backslashes in Windows paths somehow. Here, we use the double-backslash sequence to do this. The second argument to the invocation is the universal pattern for file names; if you change the asterisks to a string, you can actually filter your files. The third argument is the enumerated constant SearchOption.AllDirectories, which indicates you want a recursive file search.
In early versions of the .NET Framework, it may have been necessary to implement custom recursive file search algorithms. Some books contain excellent custom implementations, and Dot Net Perls provides a stack-based method. However, these methods are unnecessary because they overlap with existing functionality in most cases. Therefore, Dot Net Perls recommends that you use the example code shown here, not on the previous article.
(See Recursive File and Directory Method.)
In this short tutorial, we examined an overloaded version of the Directory.GetFiles method that allows you to perform a recursive file listing. Instead of implementing elaborate custom implementations, this method overload provides a clearer and simpler abstraction. While implementing custom recursion and stack-based methods is elucidating, using a proven method developed at Microsoft is more effective in typical programming contexts.