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?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
You need to use the
Security
namespace.See this SO answer.
From the answers:
Update: (following comments)
FileIOPermission
deals with security policies not filesystem permissions, so you need to useDirectoryInfo.GetAccessControl
.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
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.