gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:36:30 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com