The Directory class (from System.IO namespace) has the method required and you don't need the For Each loop
Dim path As String = "C:\test"
Dim txt As String = "*.txt"
ListBox1.Items.AddRange(Directory.EnumerateFiles(path, txt, SearchOption.AllDirectories ).ToArray())
Keep in mind that any tentative to read reserved file system folders like C:\System Volume Information
will result in a UnauthorizedAccessException so, if your path variable is dynamic, then be prepared to catch eventually any exception raised by this call
EDIT
This is the conversion in VB.NET of the procedure shown by Mr Gravell in this question where he explains a method to traverse all the directories from the root of the system drive without stopping at the exceptions thrown by certain system folders (like System Volume Information
or Program
)
Delegate Sub ProcessFileDelegate(ByVal path As String)
Sub Main
Dim path = "c:\"
Dim ext = "*.txt"
Dim runProcess As ProcessFileDelegate = AddressOf ProcessFile
ApplyAllFiles(path, ext, runProcess)
End Sub
Sub ProcessFile(ByVal path As String)
' This is the sub where you process the filename passed in'
' you add it to your listbox or to some kind of collection '
ListBox1.Items.Add(path)
End Sub
' This is the recursive procedure that traverse all the directory and'
' pass each filename to the delegate that adds the file to the listbox'
Sub ApplyAllFiles(ByVal folder As String, ByVal extension As String, ByVal fileAction As ProcessFileDelegate)
For Each file In Directory.GetFiles(folder, extension)
fileAction.Invoke(file)
Next
For Each subDir In Directory.GetDirectories(folder)
Try
ApplyAllFiles(subDir, extension, fileAction)
Catch ex As Exception
' Console.WriteLine(ex.Message)'
' Or simply do nothing '
End Try
Next
End Sub