C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You can see that the first level files in the specified directory are printed, and then all subdirectory files as well.
ArrayArgument 1: The first argument to Directory.GetFiles is the starting path. You must escape the backslashes in Windows paths.
Argument 2: The second argument is the universal pattern for file names. If you change the asterisks to a string, you can filter files.
Argument 3: The third argument is the enumerated constant SearchOption.AllDirectories, which indicates you want a recursive file search.
EnumC# program that lists files recursively
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
C:\PerlsComStage\Default.aspx
C:\PerlsComStage\Global.asax
C:\PerlsComStage\Web.config
C:\PerlsComStage\bin\PerlsComWebProject1.dll
C:\PerlsComStage\bin\PerlsComWebProject1.pdb
Note: In early versions of the .NET Framework, it may have been necessary to implement custom recursive file search algorithms.
But: Today these methods are unnecessary because they overlap with existing functionality.
C# program that gets file List
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);
}
}
Output
22
Tip: With EnumerateFiles, we receive an IEnumerable<string>. This must be evaluated in a foreach-loop or extension method.
IEnumerableNote: Thanks to Csaba Toth for pointing out the EnumerateFiles method, added in the .NET Framework 4.0.
C# program that uses EnumerateFiles
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);
}
}
}
Output
c:\files\index.html
c:\files\style.css
c:\files\images\logo.png
c:\files\images\picture.jpg
But: For real programs, using AllDirectories is probably a much better choice due to its well-tested implementation.