Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Check if directory is accessible without exception handling

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?

like image 841
SharpAffair Avatar asked Feb 25 '10 18:02

SharpAffair


People also ask

How can I tell if a directory is available or not in C#?

The Directory static class in the System.IO namespace provides the Exists() method to check the existence of a directory on the disk. This method takes the path of the directory as a string input, and returns true if the directory exists at the specified path; otherwise, it returns false.

How do you check if a file is being used by another process in Windows C#?

First check if the file exists (File. Exists) if so try to open for write within try and catch block, if exception is generated then it is used by another process.


2 Answers

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.

like image 165
Oded Avatar answered Oct 16 '22 06:10

Oded


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

  • http://blogs.msdn.com/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx
like image 25
JaredPar Avatar answered Oct 16 '22 06:10

JaredPar