.NET - Check if directory is accessible without exception handling

SharpAffair picture SharpAffair · Feb 25, 2010 · Viewed 15k times · Source

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?

Answer

Oded picture Oded · Feb 25, 2010

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.