设置要继承的文件的ACL

时间:2012-10-10 04:17:28

标签: c# acl

我正在寻找一种方法在c#中重置文件的权限,以便从父项继承,就像创建文件或将文件复制到该目录一样。

我似乎无法从文件的角度找到任何内容(我找到了一个或两个目录的参考,但由于某种原因我无法将它们翻译成文件) 。例如C# - Windows ACL - Applying Inherited Permissions。但是我不确定LOGON_USER_NAME的值应该是什么,并且我可以得到的是System.ArgumentExcpetion“无法设置标志”

2 个答案:

答案 0 :(得分:16)

我终于在这里找到了答案。 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行解决方案......

答案 1 :(得分:6)

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

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