13

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

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

4

2 回答 2

19

I finally found the answer over here. File.Move does not inherit permissions from target directory?

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

Update

While the code snip above does add in the inherited permissions, it does not remove any existing explicit permissions. My final code looks more like this.

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);

Update 2

Or, simply use TGasdf's more concise 3 line solution that is elsewhere on this page...

于 2012-10-10T14:27:51.797 回答
18

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

var fs = new System.Security.AccessControl.FileSecurity();
fs.SetAccessRuleProtection(false, false);
File.SetAccessControl(destination, fs);
于 2016-10-10T12:27:39.067 回答