【问题标题】:How to skip Directory or file when UnauthorizedAccessException occurs发生 UnauthorizedAccessException 时如何跳过目录或文件
【发布时间】:2018-11-07 13:28:26
【问题描述】:

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

【问题讨论】:

  • for each 中的 try-catch 应该可以解决问题

标签: .net vb.net exception unauthorizedaccessexcepti


【解决方案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

【讨论】:

  • 让我再检查一次......因为我之前已经应用过这个,但是在打破循环时它会关闭我的应用程序
  • 请注意,Option Infer On 中的大部分 As String 等都可以省略。
【解决方案2】:

对 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 中提供无法访问的路径,如果您不添加它将关闭您的应用程序。

【讨论】:

  • 但是您遇到了同样的异常。这不会抓住一条不存在的路径。另外,请适当缩进您的代码以使其更具可读性。
猜你喜欢
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2012-04-19
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多