如何绕过/忽略“访问路径被拒绝”/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\' 被拒绝。”。请帮助我...
谢谢,
最佳答案
最好的方法是添加一个 Try/Catch block处理异常...
try
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
catch (Exception ex)
{
//Do something when you dont have access
return null;//if you return null remember to handle it in calling code
}
您还可以专门处理 UnauthorizedAccessException如果您正在此函数中执行其他代码并且您想要确保它是导致它失败的访问异常(此异常由 Directory.GetFiles 函数抛出)...
try
{
//...
}
catch(UnauthorizedAccessException ex)
{
//User cannot access directory
}
catch(Exception ex)
{
//a different exception
}
编辑:正如下面评论中所指出的,您似乎正在使用 GetFiles 函数调用进行递归搜索。如果您希望它绕过任何错误并继续,那么您将需要编写自己的递归函数。 There is a great example here那会做你需要的。这是一个应该正是您需要的修改...
List<string> DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files;
}
关于c# - 如何在 C# 中忽略 "Access to the path is denied"/UnauthorizedAccess 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877516/