.NET - Check if directory is accessible without exception handling
Asked Answered
R

3

15

I need to go through various directories on the computer (via DirectoryInfo). Some of them aren't accessible, and UnauthorizedAccessException occurs. How can I check directory access without catching the exception?

Rigi answered 25/2, 2010 at 18:46 Comment(0)
S
12

You need to use the Security namespace.

See this SO answer.

From the answers:

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
  //No permission. 
  //Either throw an exception so this can be handled by a calling function
  //or inform the user that they do not have permission to write to the folder and return.
}

Update: (following comments)

FileIOPermission deals with security policies not filesystem permissions, so you need to use DirectoryInfo.GetAccessControl.

Stoops answered 25/2, 2010 at 18:48 Comment(5)
I tried the following: Dim readPermission As New FileIOPermission(FileIOPermissionAccess.Read, "C:\Users\Admin\Documents\My Pictures") The above directory access attempt produces "Access Denied", but "SecurityManager.IsGranted(readPermission)" always returns true.Rigi
From msdn.microsoft.com/en-us/library/…: Granting of permissions is determined by policy and is different from a demand subject to overrides, such as an assert. Also, IsGranted only tests the grant of the calling code assembly, independent of other callers on the stack.Stoops
That is not the correct answer. FileIOPermission deals with CAS, not the file system. In other words, whether the .NET security policy allows access. You can have CAS access but Windows can still deny it. DirectoryInfo.GetAccessControl() is needed.Corder
@HansPassant DirectoryInfo.GetAccessControl() may throw an exception when no read permission rights are granted. But there still may be the right to list the folder content. In this case GetAccessControl() won't help.Vietnamese
Just in case anyone is interested, I made a little snippet using GetAccessControl hereRapine
L
11

Simply put you can't. There is no way to check if a directory is accessible, all you can determine is that it was accessible. The reason why is as soon as the check completes the permissions can changed and invalidate your check. The most reliable strategy you can implement is to access the directories and catch the UnauthorizedAccessException.

I wrote a blog article on this subject recently which goes into a bit of detail here

Locket answered 25/2, 2010 at 18:56 Comment(0)
A
-1

you could just make a simple little boolean function and have a directory info variable try to get directories from a given path. if it goes through with no problem, return true, if exception is handle, return false, or break down your exception clause to sub exceptions and get the error code.

Altricial answered 18/5, 2010 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.