Melon NG
Melon NG

Reputation: 3004

How can I get whether directory accessible without try&catch?

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.

Upvotes: 1

Views: 652

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131722

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.

Upvotes: 3

pyordanov11
pyordanov11

Reputation: 870

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

Upvotes: 0

Related Questions