开发者

Does anyone have a WORKING example that displays a directory tree structure in a TreeView for VB .NET?

I have looked everywhere and cannot find a version that works. The ones I found are all either outdated or have errors.

I have something that is working for the most part, but I'm having some trouble with restricted-access folders.

The code I'm using is as follows:

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 Direc开发者_运维百科toryInfo(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

For testing purposes I replaced this section...

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

...with this...

If drive.toString = "L:\"
    PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If

...and it worked fine for that drive. The L:\ is a removable USB drive by the way.

However, with the original code I get debug errors on some folders because they are access-restricted. Is there any way to ignore those particular folders and show the rest?


Yes, you need to tighten the scope of your try catch block. You are catching the error too far away from where it occurs. Try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜