C# How to get Read/Write permissions of another user?

1.1k views Asked by At

I need to check the Read/Write permissions on a certain path. But the big problem is, I don't want to check my own instead I want to check them for another user.

This checks the user who runs the program.

System.Security.Principal.NTAccount

How am I able to check for example the user "OTHERUSER"?

This is my code so far.

   private Boolean CheckZugriff(string str_projektpfad)
    {
        str_projektpfad = Path.GetDirectoryName(str_projektpfad);
        bool isWriteAccess = false;
        try
        {
            AuthorizationRuleCollection collection = Directory.GetAccessControl(str_projektpfad).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
            foreach (FileSystemAccessRule rule in collection)
            {
                if (rule.AccessControlType == AccessControlType.Allow)
                {
                    isWriteAccess = true;
                    break;
                }
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            isWriteAccess = false;
        }
        catch (Exception ex)
        {
            isWriteAccess = false;

        }
        if (!isWriteAccess)
        {
            //handle notifications                 
        }

        return isWriteAccess;
    }
1

There are 1 answers

3
Fabjan On BEST ANSWER

Found two things that may help you...

1) This code checks what permissions set for the folder for all users:

    string directory = "your path";

    DirectoryInfo di = new DirectoryInfo(directory);

    DirectorySecurity ds = di.GetAccessControl();

2) This code checks if your user has administrator rights :

bool isElevated;
WindowsIdentity identity = new WindowsIdentity("user principal name goes here");
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

It's logical that if user is not an admin and there is no rule set for him - he cannot access the folder. Not sure if it address your problem but hope it helps.