how can you easily check if access is denied for a file in .NET?

后端 未结 6 541
无人及你
无人及你 2020-11-22 14:13

Basically, I would like to check if I have rights to open the file before I actually try to open it; I do not want to use a try/catch for this check unless I have to. Is the

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 15:00

    Here is the solution you are looking for

    var fileIOPermission = new FileIOPermission(FileIOPermissionAccess.Read,
                                                System.Security.AccessControl.AccessControlActions.View,
                                                MyPath);
    
    if (fileIOPermission.AllFiles == FileIOPermissionAccess.Read)
    {
        // Do your thing here...
    }
    

    this creates a new permission of read based on view for path of all files then checks if it's equal to file access read.

提交回复
热议问题