Make Directory.GetFiles () ignore protected folders

I use the Directory.GetFiles () method to get a list of files to work with. This method throws a UnauthorizedAccessException, for example, when trying to access a protected folder. I would just skip these folders and continue. How can I accomplish this using Directory.GetFiles (preferred) or another method?

Update:

Here is the code that throws the exception. I ask the user to select a directory and then get a list of files. I commented on the code (so now this is a whole method) that iterates through the files, and the problem still arises. An exception is thrown in 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);
+3
source share
1 answer

, , . :

foreach(string filePath in Directory.GetFiles(blah))
{
   try
   {
      //do something with file
   }
   catch(UnauthorizedAccessException ex)
   {
      //email yourself about exception or just log it somewhere.
   }
}
+4

Source: https://habr.com/ru/post/1792109/


All Articles