UnauthorizedAccessException

UnauthorizedAccessException

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

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 做一个过滤器来忽略包含文件夹名称的任何文件夹,但这不起作用,它只是在文件夹名称处停止了我的程序。

最佳答案

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



简短报价:



解决方案:

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/

10-09 18:20