它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
。