vb.net - FileSystem.GetFiles()+ UnauthorizedAccessException错误?

标签 vb.net file error-handling find

seems like FileSystem.GetFiles()无法从.Net在尝试访问禁区目录时触发的UnauthorizedAccessException异常中恢复。

在这种情况下,这是否意味着该类/方法在扫描整个驱动器时没有用,我应该使用其他解决方案(在哪种情况下:哪个?)?

这是一些显示问题的代码:

Private Sub bgrLongProcess_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgrLongProcess.DoWork
    Dim drive As DriveInfo
    Dim filelist As Collections.ObjectModel.ReadOnlyCollection(Of String)
    Dim filepath As String

    'Scan all fixed-drives for MyFiles.*
    For Each drive In DriveInfo.GetDrives()
        If drive.DriveType = DriveType.Fixed Then
            Try
                'How to handle "Access to the path 'C:\System Volume Information' is denied." error?
                filelist = My.Computer.FileSystem.GetFiles(drive.ToString, FileIO.SearchOption.SearchAllSubDirectories, "MyFiles.*")
                For Each filepath In filelist
                  DataGridView1.Rows.Add(filepath.ToString, "temp")
                  'Trigger ProgressChanged() event
                  bgrLongProcess.ReportProgress(0, filepath)
                Next filepath
            Catch Ex As UnauthorizedAccessException
                'How to ignore this directory and move on?
            End Try
        End If
    Next drive
End Sub

谢谢。

编辑:如何仅使用Try/Catch来让GetFiles()填充数组,忽略异常并恢复?
Private Sub bgrLongProcess_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgrLongProcess.DoWork
    'Do lengthy stuff here
    Dim filelist As Collections.ObjectModel.ReadOnlyCollection(Of String)
    Dim filepath As String

    filelist = Nothing
    Try
        filelist = My.Computer.FileSystem.GetFiles("C:\", FileIO.SearchOption.SearchAllSubDirectories, "MyFiles.*")
    Catch ex As UnauthorizedAccessException
        'How to just ignore this off-limit directory and resume searching?
    End Try

    'Object reference not set to an instance of an object
    For Each filepath In filelist
        bgrLongProcess.ReportProgress(0, filepath)
    Next filepath
End Sub

最佳答案

将您的try catch语句放入For each filepate in filelist循环中。因为现在,当您捕获UnauthorizedAccessException时,将跳过其余的filelist项。

编辑

你是对的。引发异常时,try-catch开销很大,通常您想在引发异常之前尝试检测这种情况。在这种情况下,执行此操作的一种方法是在执行任何操作之前检查对文件的访问权限。

对于目录,有this GetAccessControl函数。有is a similar function文件。

您可能必须中断GetFiles函数才能仅最初获取目录,然后递归地遍历每个目录,始终为每个目录和文件调用GetAccessControl

关于vb.net - FileSystem.GetFiles()+ UnauthorizedAccessException错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2449700/

相关文章:

Excel VBA - 网页抓取 - 跟踪包裹 - 处理跟踪号不正确的错误

php - Laravel在表单提交之前显示错误消息

vb.net - 调用函数 vb.net 时 mybase.load 停止加载

vb.net - 本地化.NET;使用 ResourceManager 时的后备语言

java - 字符串数组名称搜索

java - 将文本从文件复制到 HttpServletResponse 的最快方法

.net - 方法摘要XML注释的良好做法

vb.net - 如何更新数据表

Java BufferedReader 回到文本文件的顶部?

python - 尝试将二进制转换为十进制: ended with a weird int error?