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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: