9

检查以下两个代码块:

System.Security.AccessControl.DirectorySecurity dsec = System.IO.Directory.GetAccessControl(str);
System.Security.Principal.NTAccount group= new System.Security.Principal.NTAccount("DOMAIN","USERGROUP");
System.Security.AccessControl.FileSystemAccessRule myrule = new System.Security.AccessControl.FileSystemAccessRule(group,System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
dsec.SetAccessRule(myrule);
System.IO.Directory.SetAccessControl(str,dsec);

System.Security.AccessControl.FileSecurity fsec = System.IO.File.GetAccessControl(file);
System.Security.Principal.NTAccount group= new System.Security.Principal.NTAccount("DOMAIN","USERGROUP");
System.Security.AccessControl.FileSystemAccessRule myrule = new System.Security.AccessControl.FileSystemAccessRule(group,System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
fsec.SetAccessRule(myrule);
System.IO.File.SetAccessControl(file,fsec);

人们会期望它们都做完全相同的事情,只有一个对目录和一个文件。而且,在某些方面,他们确实如此。在这两种情况下,所讨论的文件系统对象都会发生变化,因此 DOMAIN\USERGROUP 具有完全控制的有效权限。

但是,奇怪的是,当您右键单击文件并查看安全性时,您会看到: 文件安全选项卡

当您右键单击文件夹并查看安全性时,您会看到: 文件夹安全选项卡

如果我然后转到 Advanced->Effective Permissions->Select(DOMAIN\USERGROUP),它显示该组的文件夹的有效权限是完全控制(所有框都被选中,而不仅仅是完全控制框. 那会更奇怪)。

我的问题是,为什么几乎相同的实现的效果会有所不同,有人知道如何复制将权限应用于文件的效果吗?

4

2 回答 2

12

不同之处在于传播标志与目录安全性的相关性。

var accessRule = new FileSystemAccessRule(
    identity: group,
    fileSystemRights: FileSystemRights.FullControl,
    type: AccessControlType.Allow,
    inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    propagationFlags: PropagationFlags.None);

注意inheritanceFlags设置。如果未指定,默认为无,它被归类为“特殊”。

于 2013-01-16T06:36:35.320 回答
0

关于向文件添加权限,您可以尝试 Logan

如果有帮助,请尝试此代码

    public static bool CheckReadWriteAccces(string filePath, System.Security.AccessControl.FileSystemRights fileSystemRights)
    {
        FileInfo fileInfo = new FileInfo(filePath);

        string str = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper();
        foreach (System.Security.AccessControl.FileSystemAccessRule rule in fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        {
            if (str == rule.IdentityReference.Value.ToUpper())
                return ((rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow) && (fileSystemRights == (rule.FileSystemRights & fileSystemRights)));
        }

        return false;
    }


    /// <summary>
    /// Make a file writteble
    /// </summary>
    /// <param name="path">File name to change</param>
    public static void MakeWritable(string path)
    {
        if (!File.Exists(path))
            return;
        File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
    }
于 2012-08-07T18:45:29.447 回答