[英]C# Directory.GetDirectories - how to workaround UnauthorizedAccessException?
[英]UnauthorizedAccessException with getDirectories
大家好,我目前通过此次调用获得了我想要的子目录:
foreach (DirectoryInfo dir in parent)
{
try
{
subDirectories = dir.GetDirectories().Where(d => d.Exists == true).ToArray();
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
}
foreach (DirectoryInfo subdir in subDirectories)
{
Console.WriteLine(subdir);
var temp = new List<DirectoryInfo>();
temp = subdir.GetDirectories("*", SearchOption.AllDirectories).Where(d => reg.IsMatch(d.Name)).Where((d => !d.FullName.EndsWith("TESTS"))).Where(d => !(d.GetDirectories().Length == 0 && d.GetFiles().Length == 0)).Where(d => d.GetFiles().Length > 3).ToList();
candidates.AddRange(temp);
}
}
foreach(DirectoryInfo dir in candidates)
{
Console.WriteLine(dir);
}
所以现在我的问题是我的最终列表称为候选人我什么都没得到,因为我得到一个访问问题,因为在try块中我的子目录文件夹中有一个名为lost +的文件夹。 我尝试使用try和catch来处理异常,所以我可以继续做我的检查我实际上不关心这个文件夹,我试图忽略它但我不知道怎么去忽略它我的get目录搜索任何想法? 我已经尝试使用.where来做一个过滤器来忽略任何包含文件夹名称的文件夹但是它没有用,它只是在文件夹名称中停止了我的程序。
我有关于此异常( UnauthorizedAccessException
)的相同问题( ResourceContext.GetForCurrentView调用异常 ),此链接给出了为什么会发生这种情况的原因的答案:
简短的报价:
...其中的关键是您尝试读取的某些文件夹可以配置为使当前用户无法访问它们。 该方法抛出UnauthorizedAccessException,而不是忽略您有权限访问的文件夹。 但是,我们可以通过创建自己的递归文件夹搜索代码来规避这个问题。 ...
解:
private static void ShowAllFoldersUnder(string path, int indent)
{
try
{
foreach (string folder in Directory.GetDirectories(path))
{
Console.WriteLine("{0}{1}", new string(' ', indent), Path.GetFileName(folder));
ShowAllFoldersUnder(folder, indent + 2);
}
}
catch (UnauthorizedAccessException) { }
}
您可以像Microsoft解释的那样使用递归: 链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.