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

Cannot set Full Control permission for folder

我正在尝试通过 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);

您需要指定继承标志:

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

方法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");