Cannot set Full Control permission for folder
Asked Answered
S

2

5

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);

folder permissions

Sneak answered 26/3, 2019 at 8:46 Comment(0)
U
5

You need to specify the inheritance flags:

directorySecurity.AddAccessRule(new FileSystemAccessRule(@"NT Service\FileMoverService",
    FileSystemRights.FullControl,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.None,
    AccessControlType.Allow));
Ut answered 26/3, 2019 at 8:56 Comment(0)
L
3

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");
Lamb answered 26/3, 2019 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.