1

我正在寻找在树视图中显示所有驱动器、文件和子文件夹的最简单方法。如果有人有一段代码可以做到这一点,他们不介意分享,我将不胜感激。

我得到的最接近的是我尝试使用的这段代码,但它给了我一个“IOException is unhandled”错误,说“设备尚未准备好”。运行时出错(大约 5-10 秒后)在下面的行

Dim folders() As String = IO.Directory.GetDirectories(dir)

下面是其余的代码

Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim drives As System.Collections.ObjectModel.ReadOnlyCollection(Of IO.DriveInfo) = My.Computer.FileSystem.Drives
    Dim rootDir As String = String.Empty
    For i As Integer = 0 To drives.Count - 1
        rootDir = drives(i).Name
        TreeView1.Nodes.Add(rootDir)
        PopulateTreeView(rootDir, TreeView1.Nodes(i))
    Next
End Sub

Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
    Dim folder As String = String.Empty
    Try
        Dim folders() As String = IO.Directory.GetDirectories(dir)
        If folders.Length <> 0 Then
            Dim childNode As TreeNode = Nothing
            For Each folder In folders
                childNode = New TreeNode(folder)
                parentNode.Nodes.Add(childNode)
                PopulateTreeView(folder, childNode)
            Next
        End If
    Catch ex As UnauthorizedAccessException
        parentNode.Nodes.Add(folder & ": Access Denied")
    End Try
End Sub
4

1 回答 1

1

看来你有一个好的开始。您收到的IOException最有可能是由于您的程序试图列出空磁盘驱动器上的内容,这显然是不可能的。

修复很简单:

For i As Integer = 0 To drives.Count - 1
    If Not drives(i).IsReady Then
        Continue For
    End If
    rootDir = drives(i).Name
    TreeView1.Nodes.Add(rootDir)
    PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next

除此之外,我建议在单击节点之前不要加载文件夹内容。将递归调用限制为 1 级(当前目录 + 其所有子目录的内容)。这样,您可以获得最佳性能,同时仍然能够确定子目录是否应该具有树视图展开按钮。

于 2013-08-06T22:27:00.323 回答