Los*_*ary 1 c# windows file-io try-catch
如何绕过/忽略 "拒绝访问路径"/ UnauthorizedAccess异常
并继续在此方法中收集文件名;
public static string[] GetFilesAndFoldersCMethod(string path)
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
Run Code Online (Sandbox Code Playgroud)
//打电话......
foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
{
Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)
我的应用程序在GetFilesAndFoldersCMethod的第一行停止,一个异常说; "拒绝访问路径'C:\ @ Logs \'." 请帮我...
谢谢,
最好的方法是添加一个Try/Catch块来处理异常......
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
}
Run Code Online (Sandbox Code Playgroud)
如果您在此函数中执行其他代码并且您希望确保它是导致其失败的访问异常(Directory.GetFiles函数抛出此异常),您还可以专门处理UnauthorizedAccessException ...
try
{
//...
}
catch(UnauthorizedAccessException ex)
{
//User cannot access directory
}
catch(Exception ex)
{
//a different exception
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如下面的评论中指出的那样,您似乎正在使用GetFiles函数调用进行递归搜索.如果你想要绕过任何错误并继续,那么你需要编写自己的递归函数.这里有一个很好的例子可以满足您的需求.这是一个修改,应该是你需要的......
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;
}
Run Code Online (Sandbox Code Playgroud)