【问题标题】:UnauthorizedAccessException with getDirectories带有 getDirectories 的 UnauthorizedAccessException
【发布时间】:2016-05-25 15:22:10
【问题描述】:

大家好,我目前通过此调用获得了我想要的子目录:

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+found 的文件夹。我尝试使用 try 和 catch 来处理异常,所以我可以继续检查我实际上并不关心这个文件夹并且我试图忽略它但我不知道如何从我的 get 目录搜索中忽略它想法?我已经尝试使用 .where 进行过滤,以忽略包含文件夹名称的任何文件夹,但这不起作用,它只是在文件夹名称处停止了我的程序。

【问题讨论】:

  • 这个问题已经回答了,看下面:link
  • 这是用于获取文件,但我需要目录而不是文件
  • 您是否尝试过使用Directory.EnumerateDirectories()?它提供了更多的灵活性,并允许您至少在找到目录时获取它们的名称。不幸的是,像lost+found 这样的隐藏系统目录会导致UnauthorizedAccessException。确保使用默认的SearchOption,这样搜索就不会自动尝试进入任何子目录。
  • 程序在此之前失败,当:'code'subDirectories = dir.GetDirectories();'code'

标签: c# unauthorizedaccessexcepti getdirectories


【解决方案1】:

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

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

短引号:

... 其中的关键是您尝试访问的某些文件夹 read 可以配置为使当前用户不能访问它们。 而不是忽略您具有限制访问权限的文件夹, 方法抛出 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) { }
}

【讨论】:

    【解决方案2】:

    您可以像 Microsoft 解释的那样使用递归:link

    【讨论】:

    • 这与我做的有什么不同,我只是在我的 prog 失败的区域使用 try and catch 块,我尝试了多种方法来处理 catch 部分,但它仍然失败并且不忽略失败。
    • 如果在遍历目录之前获取目录,在尝试 getDirectories 调用时,catch 不会影响 foreach 并打破它
    猜你喜欢
    • 1970-01-01
    • 2014-11-04
    • 2010-09-16
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多