Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

How to give a folder access rights to a particular user and revoke from everyone else? (C#)

Let's say you need to create a folder on behalf of a user and protect it from access by anyone but this user. Use DirectorySecurity.SetAccessRuleProtection procedure like this:

 DirectoryInfo  dir = new  DirectoryInfo (DirPath);
 if  (!dir.Exists)
 {
     dir.Create();
     DirectorySecurity  ds = dir.GetAccessControl();
     ds.SetAccessRuleProtection(true , false );
     ds.AddAccessRule(new  FileSystemAccessRule (DomainName + "\\\\"  + UserName,
         FileSystemRights .FullControl, AccessControlType .Allow));
     dir.SetAccessControl(ds);
 }
 

Please be noted that local administrator could request and get access rights even for protected folders. Admins are admins.

Add comment