It seems like FileSystem.GetFiles()无法从UnauthorizedAccessException异常中恢复,当尝试访问非限制目录时.Net触发。FileSystem.GetFiles()+ 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是昂贵的,不应该放在一个循环。如何使用Try/Catch来填充FileSystem.GetFiles()数组? – Gulbahar 2010-03-16 11:07:27
谢谢,我会检查出GetAccessControl,这样我可以恢复以防止这个目录被禁止。 – Gulbahar 2010-03-25 12:08:26