UnauthorizedAccessException with getDirectories

两盒软妹~` 提交于 2019-12-12 12:23:58

问题


Hello everyone I currently got subdirectories I wanted through this call:

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

so now my issue is that my final list called candidates I get nothing because im getting an access issue due to one of the folders called lost+found in my subdirectories folder in the try block. I tried using try and catch to handle the exception so I could keep doing my checks I actually dont care about this folder and im trying to just ignore it but I'm not sure how to go about ignoring it out of my get directories search any thoughts? I already tried doing a filter with .where to ignore any folder that contained the folder name but that didnt work either it just stopped my program at the folder name.


回答1:


I have the same question (ResourceContext.GetForCurrentView call exception) about this exception (UnauthorizedAccessException), and this link gives an answer to the reason why this happens:

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

Short quote:

... 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. ...

solution:

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:


You can use recursion like Microsoft explains: link.



来源:https://stackoverflow.com/questions/37441459/unauthorizedaccessexception-with-getdirectories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!