发生UnauthorizedAccessException时如何跳过目录或文件

How to skip Directory or file when UnauthorizedAccessException occurs

代码如下。我试图从 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    

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

Gabriel Luci 的回答修改:

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 中提供无法访问的路径,那么这样做并添加一个捕获将有所帮助,如果您不添加它将关闭您的应用程序。