How to ignore "Access to the path is denied" / UnauthorizedAccess Exception in C#?

13,040

Solution 1

Best way to do this is to add a Try/Catch block to handle the exception...

try
{
   string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
   return filenames;
}
catch (Exception ex)
{
   //Do something when you dont have access
   return null;//if you return null remember to handle it in calling code
}

you can also specifically handle the UnauthorizedAccessException if you are doing other code in this function and you want to make sure it is an access exception that causes it to fail (this exception is thrown by the Directory.GetFiles function)...

try
{
   //...
}
catch(UnauthorizedAccessException ex)
{
    //User cannot access directory
}
catch(Exception ex)
{
    //a different exception
}

EDIT: As pointed out in the comments below it appears you are doing a recursive search with the GetFiles function call. If you want this to bypass any errors and carry on then you will need to write your own recursive function. There is a great example here that will do what you need. Here is a modification which should be exactly what you need...

List<string> DirSearch(string sDir) 
{
   List<string> files = new List<string>();

   try  
   {
      foreach (string f in Directory.GetFiles(sDir)) 
      {
         files.Add(f);
      }

      foreach (string d in Directory.GetDirectories(sDir)) 
      {
         files.AddRange(DirSearch(d));
      }
   }
   catch (System.Exception excpt) 
   {
      Console.WriteLine(excpt.Message);
   }

   return files;
}

Solution 2

Have a look at this article in the c# programming guide:

How to: Iterate Through a Directory Tree (C# Programming Guide)

Share:
13,040
Lost_In_Library
Author by

Lost_In_Library

Computer engineer without high ego.

Updated on June 13, 2022

Comments

  • Lost_In_Library
    Lost_In_Library almost 2 years

    How to bypass/ignore "Access to the path is denied"/UnauthorizedAccess exception

    and continue to collecting filenames in this method;

    public static string[] GetFilesAndFoldersCMethod(string path)
    {
       string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
       return filenames;
    }
    

    //Calling... ...

    foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
    {
        Console.WriteLine(s);
    }
    

    My application stops on the firstline of GetFilesAndFoldersCMethod and an exception says; "Access to the path 'C:\@Logs\' is denied.". Please help me...

    Thanks,

    • David Heffernan
      David Heffernan over 12 years
      Doesn't look to me like you can request that this method continue enumerating when it encounters an error. I think you'll have to roll your own enumerator or find another class that is more flexible.
  • David Heffernan
    David Heffernan over 12 years
    Surely the enumeration will stop there too
  • musefan
    musefan over 12 years
    @DavidHeffernan: Yes, but the enumeration is on a string array - which is all files in the given directory, and as the access exception is thrown for the directory then all files will be inaccessible anyway. My assumption is that if the user is searching multiple directories then they have a loop/recursive function around the example for loop. Of course, I could be assuming wrong, will have to wait for an OP response to be sure
  • musefan
    musefan over 12 years
    @DavidHeffernan: My mistake, I now see that the GetFiles call is doing the recursive work
  • Lost_In_Library
    Lost_In_Library over 12 years
    Thank you very much for the answer. Please look at the first foreach; foreach (string f in Directory.GetFiles(d)) -> value d must be "sDir".
  • Niclas
    Niclas over 12 years
    Just a note, although the above example should work fine, if this code were to be implemented you should consider catching only UnauthorizedAccessException. As the code is now, it may give results that is hard to debug if some unexpected error should occur. (Only catch exceptions you know you can recover from!)
  • musefan
    musefan over 12 years
    @Niclas: I did already mention this is my post. The final piece of code was just a modification of the code found at the link I suggested
  • Niclas
    Niclas over 12 years
    @musefan: Yes, i saw that, but you didn't really stress it and while I'm sure you are aware of the problems that could arise from catching to generic exceptions not everyone are and I thought it was worth pointing out since it can be hard to debug...
  • sean_m
    sean_m over 8 years
    The answer here has a much more complete solution by implementing a custom iterator and doesn't use recursion, better memory footprint, also the try/catch just doesn't work in some cases.