有人有一个在 VB .NET 的 TreeView 中显示目录树结构的工作示例吗?
我到处都找过了,但找不到有效的版本。我发现的那些要么已经过时,要么有错误。
我有一些大部分工作正常的东西,但我在限制访问文件夹方面遇到了一些问题。
我正在使用的代码如下:
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 驱动器。
但是,使用原始代码时,我在某些文件夹上遇到了调试错误,因为它们是访问限制的。有什么方法可以忽略这些特定文件夹并显示其余文件夹吗?
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 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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您需要收紧 try catch 块的范围。您发现的错误距错误发生的地方太远。试试这个:
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: