gpt4 book ai didi

c# - 设置文件的ACL被继承

转载 作者:太空狗 更新时间:2023-10-29 18:04:04 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c# - 设置文件的ACL被继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com