簡體   English   中英

使用getDirectories的UnauthorizedAccessException

[英]UnauthorizedAccessException with 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);
      }

所以現在我的問題是我的最終列表稱為候選人我什么都沒得到,因為我得到一個訪問問題,因為在try塊中我的子目錄文件夾中有一個名為lost +的文件夾。 我嘗試使用try和catch來處理異常,所以我可以繼續做我的檢查我實際上不關心這個文件夾,我試圖忽略它但我不知道怎么去忽略它我的get目錄搜索任何想法? 我已經嘗試使用.where來做一個過濾器來忽略任何包含文件夾名稱的文件夾但是它沒有用,它只是在文件夾名稱中停止了我的程序。

我有關於此異常( UnauthorizedAccessException )的相同問題( ResourceContext.GetForCurrentView調用異常 ),此鏈接給出了為什么會發生這種情況的原因的答案:

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

您可以像Microsoft解釋的那樣使用遞歸: 鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM