List names of all Text files from a Directory and SubDirectories using .NET 4.0

The .NET Directory.GetFiles as well as the new Directory.EnumerateFiles (.NET 4.0 only) method has made it extremely easy to read file names with paths, that match a specified search pattern in the specified directory and subdirectories. Here’s how to search and list the names of all Text Files in a Directory as well as its SubDirectories:

C#

static void Main(string[] args)
{
try
{
string dirname = @"C:\Visual Studio 2010";
var txtFiles = Directory
.GetFiles(dirname,
"*.txt", SearchOption.AllDirectories)
.Select(nm => Path.GetFileName(nm));;
foreach (string filenm in txtFiles)
{
Console.WriteLine(filenm);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Console.ReadLine();
}

VB.NET (Converted Code)


Sub Main()
Try
Dim dirname As String = "C:\Visual Studio 2010"
Dim txtFiles = Directory.GetFiles(dirname, "*.txt", SearchOption.AllDirectories).Select(Function(nm) Path.GetFileName(nm))
For Each filenm As String In txtFiles
Console.WriteLine(filenm)
Next filenm
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

Console.ReadLine()
End Sub


OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: