3

I'm using the Directory.GetFiles() method to get a list of files to operate on. This method throws an UnauthorizedAccessException for example when trying to access a protected folder. I would like it to simply skip over such folders and continue. How can I accomplish this with either Directory.GetFiles (preferably) or another method?

Update:

Here is the code that throws the exception. I am asking the user to select a directory and then retrieving the list of files. I commented out the code (so this is now whole method) that iterates through the files and the problem still occurs. The exception is thrown on the Directory.GetFiles() line.

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult dr = fbd.ShowDialog();

if (dr == System.Windows.Forms.DialogResult.Cancel) return; 

string directory = fbd.SelectedPath;
string[] files = Directory.GetFiles(directory, "*.html", SearchOption.AllDirectories);
Kryptic
  • 1,922
  • 2
  • 21
  • 29
  • 1
    Can you post your code please? `GetFiles` shouldn't throw if one of the files detected is locked. Are you certain that the exception does not happen when you loop over the files and do something with them? – Dirk Vollmar Feb 14 '11 at 23:01
  • Does it error out on the GetFiles call or when you try to do something with the files it finds? – Abe Miessler Feb 14 '11 at 23:01
  • @0xA3 I just realized it's throwing the exception when accessing a protected directory, not the files themselves. – Kryptic Feb 14 '11 at 23:22

1 Answers1

4

If you are getting an error when you loop through the files you could throw a try catch around it, log the error and continue processing. Example:

foreach(string filePath in Directory.GetFiles(blah))
{
   try
   {
      //do something with file
   }
   catch(UnauthorizedAccessException ex)
   {
      //email yourself about exception or just log it somewhere.
   }
}
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 2
    I would have up voted this if it wasn't for the catching of `Exception`. You should always just catch the specific exception - `UnauthorizedAccessException` in this case. – ChrisF Feb 14 '11 at 23:05
  • Thanks, my problem is addressed in one of the related links, but this answer is also useful to me – Kryptic Feb 18 '11 at 04:00