I am learning VB.net, I would like to know how to get all the folders and sub-folder s inside a directory and how to add them all to a listbox. I would also like it to list the folders while it is scanning like showing the current folders found. I have tried a few things but they never seem to work. I have tried this:
Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirectoryList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
Next
For Each item In DirectoryList
ListBox1.Items.Add(item)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim DirList As New ArrayList
GetDirectories("c:\hexing\", DirList)
End Sub
Try this
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim DirList As New ArrayList
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
Next
Catch ex As Exception
End Try
End Sub
(Or)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each Dir As String In Directory.GetDirectories("c:\Program Files")
ListBox1.Items.Add(Dir)
Next
End Sub
Edit
According to VB.NET 05, List Folder, SubFolders, and Sub SubFolders:
The most efficient way would be to use recursivity:
Private Function getAllFolders(ByVal directory As String) As String()
'Create object
Dim fi As New IO.DirectoryInfo(directory)
'Array to store paths
Dim path() As String = {}
'Loop through subfolders
For Each subfolder As IO.DirectoryInfo In fi.GetDirectories()
'Add this folders name
Array.Resize(path, path.Length + 1)
path(path.Length - 1) = subfolder.FullName
'Recall function with each subdirectory
For Each s As String In getAllFolders(subfolder.FullName)
Array.Resize(path, path.Length + 1)
path(path.Length - 1) = s
Next
Next
Return path
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With