简体   繁体   中英

Visual basic 2010 - Can't list directories without showing the path

Here is my code:

Sub DataLoad()
    Dim DirList As New ArrayList
    GetDirectories("C:\Surf\Oversigt\", DirList)


    For Each item In DirList
        ListBox4.Items.Add(item)
    Next


End Sub



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
End Sub

I want only to show the name of the directories in listbox4, not the whole path of the directories. Now it would show something like this:

C:\\Surf\\Oversigt\\Foldername etc.

Please help

You could change the line

 DirectoryList.AddRange(Dirs)

with this line

DirectoryList.AddRange(Dirs.Select(Function (x) Path.GetFileName(x)).ToArray())

This will use the Path.GetFileName in an not intuitive way, but if you call GetFileName passing in a full pathname you obtain the last folder name.

However I have a doubt about your code. This code is recursive and, stripping away the full path, how could you recognize two folders with the same name but in different subfolders?

For example, suppose you have a

C:\Surf\Oversigt\MyFolder
C:\Surf\Oversigt\temp\MyFolder

You will end up in your listbox with

MyFolder
MyFolder

After the line

 Dim Dirs() As String = Directory.GetDirectories(StartPath)

simply replace the line

DirectoryList.AddRange(Dirs)

with

For Each Dir As String In Dirs
    DirectoryList.Add(Dir.Substring(Dir.LastIndexOf("\") + 1))
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM