How to loop through all the files in a directory in C#?

To loop through all the files in a directory in C#, we can use the EnumerateFiles method. The Directory.EnumerateFiles method returns an enumerable collection of file names in the specified directory.

The following code example in C# loops through the C\Temp folder and displays all files in the folder.

string root = @"C:\Temp";

// Get a list of all subdirectories

var files = from file in Directory.EnumerateFiles(root) select file;
Console.WriteLine("Files: {0}", files.Count<string>().ToString());
Console.WriteLine("List of Files");
foreach (var file in files)
{
    Console.WriteLine("{0}", file);
}

Free Book

Download the Complete free book here: Working with Directories in C#


Similar Articles