大家好,我现在通过这个调用得到了我想要的子目录:
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);
}所以现在我的问题是,我最后一个名为candidates get nothing的列表,因为在try块的子目录文件夹中,有一个名为lost+found的文件夹导致我遇到了访问问题。我试着使用try和catch来处理异常,这样我就可以继续做我的检查了,我实际上并不关心这个文件夹,我只是试图忽略它,但我不确定如何去忽略它,从我的get目录中搜索任何想法?我已经尝试过用.where过滤掉任何包含文件夹名的文件夹,但这也不起作用,它只是在文件夹名称处停止了我的程序。
发布于 2017-08-01 04:09:10
关于这个异常(UnauthorizedAccessException),我也有同样的问题(ResourceContext.GetForCurrentView call exception),这个链接给出了发生这种情况的原因的答案:
http://www.blackwasp.co.uk/FolderRecursion.aspx
简短的引述:
...其中的关键是,您尝试读取的一些文件夹可以配置为当前用户不能访问它们。该方法不是忽略您已限制访问的文件夹,而是抛出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) { }
}发布于 2016-05-25 23:57:03
你可以像微软解释的那样使用递归:link。
https://stackoverflow.com/questions/37441459
复制相似问题