user3688529 user3688529 - 6 months ago 24
Vb.net Question

vb.net ~ How to add folder names from a directory to a list box

I'm trying to add folder names from within a directpory specified by the user to a list box. I have tried a few solutions, but can't seem to add any items. Most recently I tried:

For Each folder As String In System.IO.Path.GetDirectoryName("D:\")
ListBox1.Items.Add(folder)
Next


The form was built using VB in VB Studio Express 2013. There were no errors when running the program.

If anyone can point me in the right direction, then please help!

Answer

If you want to have a list of Directories you need to call Directory.GetDirectories(path), not Path.GetDirectoryName(path) that, in your case returns just null (passing the root directory of a drive)

For Each folder As String In System.IO.Directory.GetDirectories("D:\")
    ListBox1.Items.Add(folder)
Next

if you want to show only the folder name and not the full path, just use

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

Yes, I know, it seems wrong to ask for GetFileName over a folder name, but passing a full path to GetFileName returns just the folder without the path.

Comments