无法设置文件夹的完全控制权限

时间:2019-03-26 08:46:34

标签: c# acl ntfs

我正在尝试通过C#将Full Control权限(用于NT服务帐户)添加到文件夹。但是,未设置权限,我在这里缺少什么?

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

2 个答案:

答案 0 :(得分:5)

您需要指定继承标志:

directorySecurity.AddAccessRule(new FileSystemAccessRule(@"NT Service\FileMoverService",
    FileSystemRights.FullControl,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.None,
    AccessControlType.Allow));

答案 1 :(得分:3)

方法GrantFullControl可用于为给定目录和用户设置Full Control权限。

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

只需调用如下所示的方法即可。

GrantFullControl(@"C:\Test", @"NT Service\FileMoverService");