Hey guys I was just wondering how can I add all the folders which are in a directory to a listbox. e.g. all the folders in C:\ should appear in a listbox on the form load event. How can this be done?

Thanks :D

Recommended Answers

All 6 Replies

Hi,

Your going to have to loop through all the subfolders from your starting point all the way down to where you can not find any sub folders trouble is your going to have to keep doing this for each folder you find and each of it's sub folders...

If you want to be able to give your users the option of selecting a folder why not use the FolderBrowserDialog and let them navigate?

Are you wanting all of the folders immediately under C or do you mean all of the folders in C:\ and all subfolders? For the first case you can do

ListBox1.Items.AddRange(My.Computer.FileSystem.GetDirectories("C:\").ToArray)

If you want all folders then you can do it recursively by

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    AddFolders("D:\")

End Sub

Private Sub AddFolders(root As String)

    ListBox1.Items.Add(root)

    Try
        For Each folder As String In My.Computer.FileSystem.GetDirectories(root)
            AddFolders(folder)
        Next
    Catch ex As Exception
        Debug.WriteLine(ex.Message)
    End Try

End Sub

Are you wanting all of the folders immediately under C or do you mean all of the folders in C:\ and all subfolders? For the first case you can do

This is good but how can I get only the folder names wothout showing the whole directory? Currently it's like this: C:\Users\Ahmed\AppData\Roaming.minecraft\saves
http://puu.sh/4qrHx.png

i want it with just the folder name e.g. New World, New world - Copy

GetFileName returns only the file name portion of folder

For Each folder As String In My.Computer.FileSystem.GetDirectories("D:\")
    ListBox1.Items.Add(System.IO.Path.GetFileName(folder))
Next

GetFileName returns only the file name portion of folder

Thank you Very much. :D that was what i was looking for :D

Hi,

Your going to have to loop through all the subfolders from your starting point all the way down to where you can not find any sub folders trouble is your going to have to keep doing this for each folder you find and each of it's sub folders...

If you want to be able to give your users the option of selecting a folder why not use the FolderBrowserDialog and let them navigate?

Thanks for your help too :) much appreciated as you took some of your time to take a look :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.