c# - 带有 getDirectories 的 UnauthorizedAccessException

标签 c# unauthorizedaccessexcepti 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);
      }

所以现在我的问题是,我的最终列表 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/

相关文章:

c# - 未经授权的访问异常 StreamWriter

perl - 如何按排序顺序读取目录中的文件?

c# - 应用程序栏图标名称

c# - Entity Framework 中通用类型的文本搜索

c# - SQL CLR 和可为空的日期时间参数

.net - DirectoryInfo.GetDirectories() 和属性

c# 你如何线程递归目录搜索?

c# - 如何在两个窗口之间的 Wpf 应用程序中保持 session ?

.net - System.AddIn、AddInStore.Rebuild 导致 UnauthorizedAccessException

c# - Android Unity C# : UnauthorizedAccessException writing save game data