以编程方式为“此文件夹,子文件夹和文件”分配访问控制列表(ACL)权限

时间:2012-05-14 05:49:53

标签: c# .net windows winapi

我必须使用C#.NET以编程方式为文件夹及其子文件夹和文件分配权限。我这样做如下:

var rootDic = @"C:\ROOT";
var identity = "NETWORK SERVICE"; //The name of a user account.
try
{
    var accessRule = new FileSystemAccessRule(identity,
                         fileSystemRights: FileSystemRights.Modify,
                         inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                         propagationFlags: PropagationFlags.InheritOnly,
                         type: AccessControlType.Allow);

    var directoryInfo = new DirectoryInfo(rootDic);

    // Get a DirectorySecurity object that represents the current security settings.
    DirectorySecurity dSecurity = directoryInfo.GetAccessControl();

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(accessRule);

    // Set the new access settings.
    directoryInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
    //...
}

它确实为我的C:\ ROOT'分配了权限。夹。但是它只为子文件夹和文件分配权限,但不分配' ROOT'夹。 enter image description here

问:如何定义FileSystemAccessRule实例以为ROOT文件夹,子文件夹和文件分配权限?

1 个答案:

答案 0 :(得分:12)

您只需删除PropagationFlags.InheritOnly标记即可。通过指定您声明ACE不应该应用于目标文件夹。请改用PropagationFlags.None。您可能会发现此MSDN article有用。