I'm writing a DLL to change permissions on a folder and everything underneath the folder. Below is the code that I have right now.
The problem comes when I call addPermissions(). It's correctly setting the permissions on the dirName folder and any folder that I later create under dirName, but any folder that exists when I add permissions doesn't get the additional permissions.
Do I need to recursively set the permissions on all child folders? Or is there a way to do this with a line or two of 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);
}
}
This question is old but I was looking for the same thing and found a solution:
var dirInfo = new DirectoryInfo(dirName);
var dirSecurity = dirInfo.GetAccessControl();
// Add the DirectorySystemAccessRule to the security settings.
dirSecurity.AddAccessRule(new FileSystemAccessRule(
account,
rights,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
// Set the new access settings.
dirInfo.SetAccessControl(dirSecurity);
greetings
You have to do it recursively. You can specify inheritance rules for new folders/files but for existing you have to do it yourself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.