开发者

Make Directory.GetFiles() ignore protected folders

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 oc开发者_开发技巧curs. 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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜