【问题标题】:Setting a file's ACL to be inherited将文件的 ACL 设置为继承
【发布时间】:2012-10-10 04:17:27
【问题描述】:

我正在 C# 中寻找一种方法来重置从父级继承的文件权限,就好像文件是创建或复制到该目录一样。

从 file 的角度来看,我似乎找不到任何关于此的内容(我找到了一个或两个目录参考,但由于某种原因我无法将它们转换为文件) . C# - Windows ACL - Applying Inherited Permissions,例如。但我不确定LOGON_USER_NAME 的值应该是什么,据我所知,得到一个System.ArgumentExcpetion 的“不能设置标志”

【问题讨论】:

    标签: c# acl


    【解决方案1】:

    我终于在这里找到了答案。 File.Move does not inherit permissions from target directory?

    var fs = File.GetAccessControl(destination);
    fs.SetAccessRuleProtection(false, false);
    File.SetAccessControl(destination, fs);
    

    更新

    虽然上面的代码片段确实添加了继承的权限,但它不会删除任何现有的显式权限。我的最终代码看起来更像这样。

    string destination = @"<my file>";
    FileInfo fileInfo;
    FileSecurity fileSecurity;
    FileSystemAccessRule fileRule;
    AuthorizationRuleCollection fileRules;
    
    fileInfo = new FileInfo(destination);
    fileSecurity = fileInfo.GetAccessControl();
    fileSecurity.SetAccessRuleProtection(false, false);
    /*
     * Only fetch the explicit rules since I want to keep the inherited ones. Not 
     * sure if the target type matters in this case since I am not examining the
     * IdentityReference.
     */
    fileRules = fileSecurity.GetAccessRules(includeExplicit: true, 
                             includeInherited: false, targetType: typeof(NTAccount));
    /*
     * fileRules is a AuthorizationRuleCollection object, which can contain objects 
     * other than FileSystemAccessRule (in theory), but GetAccessRules should only 
     * ever return a collection of FileSystemAccessRules, so we will just declare 
     * rule explicitly as a FileSystemAccessRule.
     */
    foreach (FileSystemAccessRule rule in fileRules)
    {
        /*
         * Remove any explicit permissions so we are just left with inherited ones.
         */
        fileSecurity.RemoveAccessRule(rule);
    }
    fileInfo.SetAccessControl(fileSecurity);
    

    更新 2

    或者,只需使用本页其他地方的 TGasdf 更简洁的 3 行解决方案...

    【讨论】:

    • 我一直在寻找这个 .. fs.SetAccessRuleProtection(false, false);诀窍:D
    【解决方案2】:

    删除显式权限的公认答案对我来说有点太复杂了,所以我尝试创建一个新的 FileSecurity。以下似乎可行,并且生成的权限仅使用继承的权限:

    var fs = new System.Security.AccessControl.FileSecurity();
    fs.SetAccessRuleProtection(false, false);
    File.SetAccessControl(destination, fs);
    

    【讨论】:

      猜你喜欢
      • 2017-05-31
      • 2014-02-26
      • 2011-11-27
      • 2011-03-17
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2022-01-13
      相关资源
      最近更新 更多