I'm trying to add the Full Control
permission (for a NT service account) to a folder through C#. However, the permission is not set, what I am missing here?
var directoryInfo = new DirectoryInfo(@"C:\Test");
var directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.AddAccessRule(new FileSystemAccessRule("NT Service\\FileMoverService",
FileSystemRights.FullControl, AccessControlType.Allow));
directoryInfo.SetAccessControl(directorySecurity);
Right-click the file or folder, and then click Properties. Click the Security tab. Under Group or user names, click your name to see the permissions you have. Click Edit, click your name, select the check boxes for the permissions that you must have, and then click OK.
Go to the Security tab and look for the user name or group section. If you do not have access to that folder, click the Advanced button. Once you are in the Advanced Security Settings window, go to the Owner section at the top, then click the Change link. Doing so should bring up the User or Group window.
You need to specify the inheritance flags:
directorySecurity.AddAccessRule(new FileSystemAccessRule(@"NT Service\FileMoverService",
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
The method GrantFullControl
can be used to set the Full Control
permission for a given directory and user.
private static void GrantFullControl(string directoryPath, string username)
{
if (!Directory.Exists(directoryPath))
return;
var directorySecurity = Directory.GetAccessControl(directoryPath);
directorySecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None,
AccessControlType.Allow));
Directory.SetAccessControl(directoryPath, directorySecurity);
}
Just call the method as shown below.
GrantFullControl(@"C:\Test", @"NT Service\FileMoverService");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With