Directory Access Control

Written by stevey on July 25th, 2010

The other day I was playing with ACL and got myself locked out of a directory that I tried to access. Then I tried to add a new FileSystemAccessRule with FullControl right and Allow type, hoping to regain the access to the folder; but it turned out that was not the way to do it. I had to call RemoveAccessRule from the DirectorySecurity object in order to re-grant myself access to the folder. So I figured I would make a note here so that myself and others can use as reference when things about ACL get murky again in the future.

To grant a Windows user access to a specific directory, use the following codes (need using these namespaces : System.Security.Principal,System.Security.AccessControl,System.IO)

 

public static void GrantDirectoryAccess(string dir, string userName)

{

DirectorySecurity ds = Directory.GetAccessControl(dir);

ds.AddAccessRule(new FileSystemAccessRule(userName,FileSystemRights.FullControl, AccessControlType.Allow));

Directory.SetAccessControl(dir,ds);

 

}

To deny user Read access to the folder, use the following:

public static void DenyDirectoryAccess(string dir, string username)

{

DirectorySecurity ds = Directory.GetAccessControl(dir);

ds.AddAccessRule(new FileSystemAccessRule(username,FileSystemRights.Read, AccessControlType.Deny));

Directory.SetAccessControl(dir,ds);

}

 

If you want to give user back the access right, you would think that by running GrantDirectoryAccess() method again you can achieve that, correct? Wrong! The ACL rule is if there are Deny and Allow access types both tied to a user or a user group, then the Deny will take precedence.

So, in order to give the access right back, you’ll need to remove the access rule by running the codes below instead:

public static void RemoveDirectoryDeny(string dir, string userName)

{

DirectorySecurity ds = Directory.GetAccessControl(dir);

ds.RemoveAccessRule(new FileSystemAccessRule(userName, FileSystemRights.Read, AccessControlType.Deny));

Directory.SetAccessControl(dir, ds);

}

Here is the sample of how to grant user “steve” access to “c:\test” folder, then deny it, thn re-grant it:

static void Main(string[] args)

{

Console.WriteLine(“Messing around with C:\test”);

//first grant fullcontrol access

GrantDirectoryAccess(@”c:\test”,”steve);

//then deny the Read access

DenyDirectoryAccess(@”c:\test”, “Steve”);

//Tried to run GrantDirectoryAccess() again and see if it worked;, it didn’t

//Had to remove the Deny rule

UserSecurity.RemoveDirectoryDeny(@”c:\test”, “Steve”);

Console.WriteLine(“Access to c:\test has been regained. Press any key to exit”);

Console.ReadKey(true);

 

}

 

 

 

Leave a Comment