简体   繁体   English

Visual Basic 2010-无法列出目录而不显示路径

[英]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. 我只想显示listbox4中目录的名称,而不是目录的整个路径。 Now it would show something like this: 现在它将显示如下内容:

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

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. 这将以一种不直观的方式使用Path.GetFileName,但是如果调用GetFileName传递完整的路径名,则将获得最后一个文件夹名。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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