有没有人有在VB.NET的TreeView中显示目录树结构的工作示例?

有没有人有在VB.NET的TreeView中显示目录树结构的工作示例?,vb.net,treeview,directory,Vb.net,Treeview,Directory,我到处都找遍了,找不到一个有效的版本。我发现的都是过时的或者有错误的 我有一些在大部分情况下都有效的东西,但我在受限访问文件夹方面遇到了一些问题 我使用的代码如下所示: Imports System.IO Public Class frmMain Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load For Each

我到处都找遍了,找不到一个有效的版本。我发现的都是过时的或者有错误的

我有一些在大部分情况下都有效的东西,但我在受限访问文件夹方面遇到了一些问题

我使用的代码如下所示:

Imports System.IO

Public Class frmMain
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each drive In DriveInfo.GetDrives
            Dim i As Integer = TreeView1.Nodes.Count

            TreeView1.Nodes.Add(drive.ToString)

            If drive.IsReady Then
                PopulateTree(drive.ToString, TreeView1.Nodes(i))
            End If
        Next
    End Sub

    Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
        Dim directory As New DirectoryInfo(sDir)

        Try
            For Each d As DirectoryInfo In directory.GetDirectories
                Dim t As New TreeNode(d.Name)

                PopulateTree(d.FullName, t)
                node.Nodes.Add(t)
            Next
        Catch excpt As UnauthorizedAccessException
            Debug.WriteLine(excpt.Message)
        End Try
    End Sub
End Class
出于测试目的,我替换了本节

If drive.IsReady Then
    PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
…用这个

If drive.toString = "L:\"
    PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
…在那次驾驶中效果很好。顺便说一下,L:\是一个可移动USB驱动器


然而,使用原始代码,我在一些文件夹上遇到调试错误,因为它们是访问受限的。是否有任何方法可以忽略这些特定文件夹并显示其余文件夹?

是的,您需要缩小try-catch块的范围。您捕捉到的错误距离发生错误的位置太远。试试这个:

Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
    Dim directory As New DirectoryInfo(sDir)


        For Each d As DirectoryInfo In directory.GetDirectories
            Dim t As New TreeNode(d.Name)

            Try
               PopulateTree(d.FullName, t)
               node.Nodes.Add(t)
            Catch excpt As UnauthorizedAccessException
               Debug.WriteLine(excpt.Message)
            EndTry
        Next

End Sub

是的,您需要收紧试抓块的范围。您捕捉到的错误距离发生错误的位置太远。试试这个:

Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
    Dim directory As New DirectoryInfo(sDir)


        For Each d As DirectoryInfo In directory.GetDirectories
            Dim t As New TreeNode(d.Name)

            Try
               PopulateTree(d.FullName, t)
               node.Nodes.Add(t)
            Catch excpt As UnauthorizedAccessException
               Debug.WriteLine(excpt.Message)
            EndTry
        Next

End Sub

调试+异常,确保所有复选框都已关闭。调试+异常,确保所有复选框都已关闭。PopulateTree例程工作正常,因此它周围的Try-Catch块似乎没有多大帮助。问题似乎出在这一行:对于每个d,在directory.GetDirectories中使用DirectoryInfo,这说明GetDirectories不起作用,因为对这些文件夹的访问受到限制。PopulateTree例程工作正常,因此围绕它的Try-Catch块似乎没有多大帮助。问题似乎出在这一行:对于每个d,在directory.GetDirectories中使用DirectoryInfo,这说明GetDirectories不起作用,因为访问限制在这些文件夹中。