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