ARTICLE

Enumerate Directory in C#

Posted by Dinesh Beniwal Articles | Files, Directory, IO July 20, 2012
In this article we will discuss about how to enumerate Directory in C#.
Reader Level:

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<string>().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<string>().ToString());
Console
.WriteLine("List of Subdirectories");
foreach
(var dir in MaDirs)
{
    Console.WriteLine("{0}",dir.Substring(dir.LastIndexOf("\\") + 1));
}


Download free book: Working with Directories in C#

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.