I am writing a DLL to change the permissions of a folder and everything below the folder. Below is the code that I have right now.
The problem occurs when I call addPermissions (). It correctly sets permissions for the dirName folder and any folder that I later create under the name dirName, but any folder that exists when adding permissions does not receive additional permissions.
Do I need to recursively set permissions for all child folders? Or is there a way to do this with a line or two code?
public class Permissions
{
public void addPermissions(string dirName, string username)
{
changePermissions(dirName, username, AccessControlType.Allow);
}
public void revokePermissions(string dirName, string username)
{
changePermissions(dirName, username, AccessControlType.Deny);
}
private void changePermissions(string dirName, string username, AccessControlType newPermission)
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo(dirName);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
string user = System.Environment.UserDomainName + "\\" + username;
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(
user,
FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ExecuteFile | FileSystemRights.Delete,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
newPermission
));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
}
source
share