views:

40

answers:

2

How do you check to se if a user has read permissions for a file in windows? There is the possibility to read the authorization rules via File.GetAccessControl. This does not tell me if the user has the right to read the file through group membership...

+1  A: 

Read the file. If you can read it, you have permission.


This is actually the intended model here. Even if you check the permissions before trying to read, there is the possibility that they will change before you get to your read. You are supposed to attempt to read the file (CreateFile will fail if you cannot) and beg forgiveness (handle the error) afterwards.

Zooba
That's only for the current user...
Wally Mathieu
Handy clarification. In that case, impersonate that user and attempt to read the file. Otherwise, what are you really trying to do here? It's possible that there is a better way.
Zooba
But, what if you need to check that a different user than the logged in user has permissions to a certain file. For instance if there is a file containing configuration and a service user (i.e. not a logged in user) reading that configuration. Assume that you're not in control over the environment this is going to be deployed in. You have no control over what the configuration managers name their groups, but can only require that they give permission to a set of files. It would be helpful to be able to check if the user can read the configuration file.
Wally Mathieu
The most robust way is still to impersonate the user (ie. programmatically start a process as the user that attempts to read the file and returns success/failure), though this does require knowing the user's credentials. Why isn't an error/log message when the user *actually* fails to read the file an option? Are you trying to fail too early?
Zooba
Also, I believe only administrators can view group membership for other users, which changes everything (permission-wise) dramatically.
Zooba
I can assume that the person checking these settings have administrative privileges. I'm going to see if it is possible to do an impersonation. I was hoping there were some other way.
Wally Mathieu
I had to fish out the password :/. But looks like it's working.
Wally Mathieu
Also, I had to do a pinvoke of the advapi32 dll...
Wally Mathieu
A: 

The C "access" runtime function can be used to check the access. I'm not sure whether it checks all Windows levels (group, user, ...). Just try it out.

Patrick
PInvoke to advapi32.dll you mean?
Wally Mathieu
http://kseesharp.blogspot.com/2009/04/c-create-windowsidentity-from-userid.html
Wally Mathieu