开发者

Make Directory.GetFiles() ignore protected folders

开发者 https://www.devze.com 2023-02-10 17:08 出处:网络
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

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

精彩评论

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

关注公众号