获取目录中的所有文件夹和子文件夹

时间:2014-02-06 05:56:29

标签: vb.net directory

我正在学习VB.net,我想知道如何获取目录中的所有文件夹和子文件夹以及如何将它们全部添加到列表框中。我还希望它在扫描时列出文件夹,如显示当前找到的文件夹。我尝试过一些东西,但它们似乎从不起作用。我试过这个:

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

3 个答案:

答案 0 :(得分:6)

试试这个

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

修改

根据VB.NET 05, List Folder, SubFolders, and Sub SubFolders

  

最有效的方法是使用递归:

 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

答案 1 :(得分:3)

使用Directory.GetDirectories方法。

DirectoryInfo dinfo = new DirectoryInfo("path");

dinfo.GetDirectories();

答案 2 :(得分:1)

最简单的是:

私有子Button2_Click(作为对象发送,作为EventArgs发送)处理Button2.Click         GetDirectories(Label1.Text)     结束

Sub GetDirectories(ByVal StartPath As String)
    For Each Dir As String In IO.Directory.GetDirectories(StartPath)
        CheckedListBox1.Items.Add(Dir)
        GetDirectories(Dir)
    Next
End Sub