我到处寻找,找不到有效的版本。我找到的那些都已过时或有错误。
我有一些在大多数情况下都有效的东西,但我在限制访问文件夹方面遇到了一些麻烦。
我正在使用的代码如下:
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驱动器。
但是,使用原始代码,我会在某些文件夹上收到调试错误,因为它们受访问限制。有没有办法忽略这些特定文件夹并显示其余文件夹?
答案 0 :(得分:3)
是的,您需要收紧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