gpt4 book ai didi

C# - 在 Windows 7 中为所有用户设置目录权限

转载 作者:可可西里 更新时间:2023-11-01 08:14:35 25 4
gpt4 key购买 nike

这应该是一个相当简单的问题,但出于某种原因,我似乎无法解决这个问题。我想要做的就是设置给定目录的权限,以允许所有用户完全访问。这是我到目前为止的代码:

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(destinationDirectory);
FileSystemAccessRule fsar = new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow);
DirectorySecurity ds = null;

if (!di.Exists)
{
System.IO.Directory.CreateDirectory(destinationDirectory);
}

ds = di.GetAccessControl();
ds.AddAccessRule(fsar);

没有抛出异常,但也没有任何反应。当我在代码运行后检查目录权限时,我没有看到任何变化。

有什么想法吗?

最佳答案

您还需要调用 SetAccessControl应用更改。

ds = di.GetAccessControl();
ds.AddAccessRule(fsar);
di.SetAccessControl(ds); // nothing happens until you do this

MSDN 上的示例似乎非常缺乏细节,正如所讨论的那样here .我破解了本文中的代码以获得以下表现良好的代码:

static bool SetAcl()
{
FileSystemRights Rights = (FileSystemRights)0;
Rights = FileSystemRights.FullControl;

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

DirectoryInfo Info = new DirectoryInfo(destinationDirectory);
DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

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

if (!Result)
return false;

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

// *** Add Access rule for the inheritance
AccessRule = new FileSystemAccessRule("Users", Rights,
iFlags,
PropagationFlags.InheritOnly,
AccessControlType.Allow);
Result = false;
Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

if (!Result)
return false;

Info.SetAccessControl(Security);

return true;
}

关于C# - 在 Windows 7 中为所有用户设置目录权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8944765/

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