Search code examples
c#windowsfile-iotry-catch

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


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,


Solution

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