如何忽略“访问路径被拒绝” / C# 中的 UnauthorizedAccess 异常?
如何绕过/忽略“访问路径被拒绝”/UnauthorizedAccess异常
并继续在此方法中收集文件名;
public static string[] GetFilesAndFoldersCMethod(string path)
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
//调用... ...
foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
{
Console.WriteLine(s);
}
我的应用程序停止在 GetFilesAndFoldersCMethod 的第一行,出现异常; “对路径‘C:\@Logs\’的访问被拒绝。”。请帮助我...
谢谢,
How to bypass/ignore "Access to the path is denied"/UnauthorizedAccess exception
and continue to collecting filenames in this method;
public static string[] GetFilesAndFoldersCMethod(string path)
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
//Calling... ...
foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
{
Console.WriteLine(s);
}
My application stops on the firstline of GetFilesAndFoldersCMethod and an exception says;
"Access to the path 'C:\@Logs\' is denied.". Please help me...
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的方法是添加 Try/ Catch 块 来处理异常...
您还可以专门处理 UnauthorizedAccessException 如果您在此函数中执行其他代码,并且您想确保它是导致其失败的访问异常(此异常是由 Directory.GetFiles 函数)...
编辑:如下面出现评论您正在使用 GetFiles 函数调用进行递归搜索。如果您希望绕过任何错误并继续,那么您将需要编写自己的递归函数。 这里有一个很好的示例,它可以满足您的需要。这是一个修改,应该正是您所需要的......
Best way to do this is to add a Try/Catch block to handle the exception...
you can also specifically handle the UnauthorizedAccessException if you are doing other code in this function and you want to make sure it is an access exception that causes it to fail (this exception is thrown by the Directory.GetFiles function)...
EDIT: As pointed out in the comments below it appears you are doing a recursive search with the GetFiles function call. If you want this to bypass any errors and carry on then you will need to write your own recursive function. There is a great example here that will do what you need. Here is a modification which should be exactly what you need...
我在 Windows 11 中遇到此错误。我以管理员身份在 PowerShell 中使用此命令解决了我的问题。
I got this error in windows 11. i solved my problem using this command in PowerShell as administrator.