[C#] How to Enumerate Directory in C#

The Directory.EnumerateDirectories method returns an enumerable collection of directory names in the specified directory.

string root = @"C:\Temp";
// Get a list of all subdirectories
var dirs = from dir in Directory.EnumerateDirectories(root) select dir;
Console.WriteLine("Subdirectories: {0}", dirs.Count().ToString());
Console.WriteLine("List of Subdirectories");
foreach (var dir in dirs)
{
    Console.WriteLine("{0}",dir.Substring(dir.LastIndexOf("\") + 1));
}
// Get a list of all subdirectories starting with 'Ma'
var MaDirs = from dir in Directory.EnumerateDirectories(root, "Ma*") select  dir;
Console.WriteLine("Subdirectories: {0}", MaDirs.Count().ToString());
Console.WriteLine("List of Subdirectories");
foreach (var dir in MaDirs)
{
    Console.WriteLine("{0}",dir.Substring(dir.LastIndexOf("\") + 1));
}

 

Xem thêm  [C#] How to Enumerate Files in C#

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *