.NET - Check if directory is accessible without exception handling

眉间皱痕 提交于 2019-12-17 19:38:44

问题


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?


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2336699/net-check-if-directory-is-accessible-without-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!