.NET - Check if directory is accessible without exception handling

后端 未结 3 578
自闭症患者
自闭症患者 2020-12-10 12:27

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 direct

3条回答
  •  庸人自扰
    2020-12-10 13:13

    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.

提交回复
热议问题