gpt4 book ai didi

C# Directory Security SetAccessControl 没有生效?

转载 作者:行者123 更新时间:2023-11-30 12:28:00 24 4
gpt4 key购买 nike

我正在尝试更改目录的权限。为此,我正在运行一个实际执行 SetAccessControl 的提升进程。

    static void Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options)) return;

var myDirectoryInfo = new DirectoryInfo(options.folder);
var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
var usr = options.user;

myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(usr, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

try
{
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}

当我以管理员身份运行时没有错误,但文件夹访问权限保持不变。有什么想法吗?

最佳答案

对我有用的答案是使用 ModifyAccessRule 首先授予目录权限。然后添加继承规则。

我还发现windows资源管理器并不总是显示当前权限,不知道是什么导致它刷新,但我注意到有时权限设置正确,我的程序可以访问目录中的文件,即使explorer 显示没有权限。

    private static bool SetAccess(string user, string folder)
{
const FileSystemRights Rights = FileSystemRights.FullControl;

// *** Add Access Rule to the actual directory itself
var AccessRule = new FileSystemAccessRule(user, Rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow);

var Info = new DirectoryInfo(folder);
var Security = Info.GetAccessControl(AccessControlSections.Access);
bool Result;

Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

if (!Result) return false;

// *** Always allow objects to inherit on a directory
const InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

// *** Add Access rule for the inheritance
AccessRule = new FileSystemAccessRule(user, Rights,
iFlags,
PropagationFlags.InheritOnly,
AccessControlType.Allow);

Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

if (!Result) return false;

Info.SetAccessControl(Security);

return true;
}

关于C# Directory Security SetAccessControl 没有生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662641/

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