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
Tweet
No comments:
Post a Comment