2014-02-06 255 views
3

我正在學習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 

回答

5

試試這個

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 
+0

第二個沒有得到所有的文件夾,我希望它獲得主目錄中的所有文件夾,然後獲得這些文件夾中的所有子文件夾。無論如何感謝 – TestUser1

+0

@ xGh0stSn1p3r看我的編輯。它會得到你所有的子文件夾 –

+0

謝謝,但在一開始,它種凍結,只停留在那裏一段時間,無法移動它或任何東西。有沒有辦法在後臺運行它,所以你仍然可以移動窗體?或者甚至每次將每個目錄添加到列表框時,每次都找到一個目錄而不僅僅是停留在那裏?感謝編輯*它只是說當列表框上的字符串[]數組 – TestUser1

3

使用Directory.GetDirectories方法。

DirectoryInfo dinfo = new DirectoryInfo("path"); 

dinfo.GetDirectories(); 
+0

我曾經嘗試這樣做,它的作品,但它並沒有在目錄中獲取的子文件夾,我希望它獲取每個文件夾中的每個子文件夾。謝謝anywa – TestUser1

相關問題