gpt4 book ai didi

c# - 带有 getDirectories 的 UnauthorizedAccessException

转载 作者:行者123 更新时间:2023-11-30 12:23:20 27 4
gpt4 key购买 nike

大家好我目前通过这个电话得到了我想要的子目录:

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 我什么也得不到,因为我遇到了访问问题,这是由于 try block 中我的子目录文件夹中名为 lost+found 的文件夹之一。我尝试使用 try 和 catch 来处理异常,这样我就可以继续检查我实际上并不关心这个文件夹,我试图忽略它,但我不确定如何从我的 get 目录搜索中忽略它想法?我已经尝试使用 .where 进行过滤以忽略包含该文件夹名称的任何文件夹,但这没有用,它只是在文件夹名称处停止了我的程序。

最佳答案

关于此异常 (UnauthorizedAccessException),我有同样的问题 ( ResourceContext.GetForCurrentView call exception),此链接给出了发生这种情况的原因的答案:

http://www.blackwasp.co.uk/FolderRecursion.aspx

简短的引用:

... Key amongst these is that some of the folders that you attempt to read could be configured so that the current user may not access them. Rather than ignoring folders to which you have restricted access, the method throws an UnauthorizedAccessException. However, we can circumvent this problem by creating our own recursive folder search code. ...

解决方法:

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) { }
}

关于c# - 带有 getDirectories 的 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com