1

Now I am about to get directories of "C:\Documents and Settings" like this:

var d=Directory.GetDirectories(@"C:\Documents and Settings")

Visual Studio reports an error:

System.UnauthorizedAccessException: 'Access to the path 'C:\Documents and Settings' is denied.'

Well, the directory is inaccessible.

I want to get to know whether the directory about to get is accessible.

Many tutorials, just like this:https://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access , are using a try&catch to avoid the error.

As we know, try&catch will slow down the speed. And also, I don't think it is the best way.

Is there any way to solve this? Thank you.

Igor
  • 60,821
  • 10
  • 100
  • 175
Melon NG
  • 2,568
  • 6
  • 27
  • 52

2 Answers2

3

This is possible in .NET Core with the GetDirectories, GetFiles, EnumerateDirectories and EnumerateFiles overloads that accept the EnumerationOptions parameter:

var options = new EnumerationOptions { IgnoreInaccessible=true };
var files=Directory.GetDirectories(somePath,"*",options);

EnumerationOptions exists only in .NET Core 2.1 and later, or .NET Standard 2.1 or later. To use it with Windows Forms or WPF applications you'll have to migrate them to .NET (Core) 5 first.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

I think Directory.Exists() should do the trick. According to the Remarks it will return false if the directory is not accessible.

MultiValidation
  • 823
  • 7
  • 21
  • It won't - how will the code know what the file's name ? – Panagiotis Kanavos Sep 14 '20 at 11:17
  • 1
    `Directory.Exists()` uses a plethora of catch blocks :) Well, yes, you cannot see them... You could check [FileIOPermission](https://learn.microsoft.com/en-us/dotnet/api/system.security.permissions.fileiopermission), which is used internally. – Jimi Sep 14 '20 at 11:19