代码在下面。我试图从特定路径以sDirPath
的形式获取文件,然后将其存储在树形视图中,基本上是制作了一个自定义文件夹浏览器对话框。但是问题是,当我获得无法访问的系统文件或文件夹时,我得到了UnauthorizedAccessException
。它发生在文件夹或文件(例如隐藏文件夹)和系统文件夹或文件上,例如C:\中的$ recyle.bin或文档和设置的快捷方式。我只想跳过这些文件夹或文件。我不想拿他们。
Dim sAllfiles() As String = Directory.GetFiles(sDirPath, "*.*")
For Each sfile As String In sAllfiles
Dim objFileInformation As FileInfo = New FileInfo(sfile)
Dim tnTreeNodeSub As TreeNode
tnTreeNodeSub=tnTreeNodeRootDirectory.Nodes.Add(objFileInformation.Name)
Next
答案 0 :(得分:1)
Try .. Catch
语句正是用于此目的。
例如,这将仅忽略UnauthorizedAccessException
。任何其他异常仍将终止循环。
Dim sAllfiles() As String = Directory.GetFiles(sDirPath, "*.*")
For Each sfile As String In sAllfiles
Try
Dim objFileInformation As FileInfo = New FileInfo(sfile)
Dim tnTreeNodeSub As TreeNode
tnTreeNodeSub=tnTreeNodeRootDirectory.Nodes.Add(objFileInformation.Name)
Catch ex As UnauthorizedAccessException
Continue For 'Ignore the exception and move on
End Try
Next
答案 1 :(得分:-1)
修改加布里埃尔·露西的答案:
Try
Dim sAllfiles() As String = Directory.GetFiles(sDirPath, "*.*")
For Each sfile As String In sAllfiles
Try
Dim objFileInformation As FileInfo = New FileInfo(sfile)
Dim tnTreeNodeSub As TreeNode
tnTreeNodeSub=tnTreeNodeRootDirectory.Nodes.Add(objFileInformation.Name)
Catch ex As UnauthorizedAccessException
Continue For 'Ignore the exception and move on
End Try
Next
Catch ex As UnauthorizedAccessException
'Ignore the exception and move on
End Try
如果您在sDirPath中直接输入了无法访问的路径(如果不添加路径),则会关闭应用程序。