为了账号安全,请及时绑定邮箱和手机立即绑定

使用C#.NET将“所有人”特权添加到文件夹

使用C#.NET将“所有人”特权添加到文件夹

拉风的咖菲猫 2019-12-27 09:37:56
我使用下面的代码允许所有人访问文件夹:System.Security.AccessControl.DirectorySecurity sec =    System.IO.Directory.GetAccessControl(directory, AccessControlSections.All);FileSystemAccessRule accRule = new FileSystemAccessRule("Everyone",                                       FileSystemRights.Modify,                                       AccessControlType.Allow);sec.AddAccessRule(accRule);    // setACLsec.ResetAccessRule(accRule);现在,将“所有人”用户添加到该文件夹中,但是没有分配任何权限。没有选中所有的读取,写入,执行等复选框。
查看完整描述

3 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

我想告诉你的第一件事是我如何找到这个解决方案的。这可能比答案更重要,因为文件权限很难正确获得。


我要做的第一件事是使用Windows对话框和复选框设置所需的权限。我为“所有人”添加了一条规则,并勾选了“完全控制”之外的所有框。


然后,我编写了此C#代码,以确切地告诉我复制Windows设置所需的参数:


string path = @"C:\Users\you\Desktop\perms"; // path to directory whose settings you have already correctly configured

DirectorySecurity sec = Directory.GetAccessControl(path);

foreach (FileSystemAccessRule acr in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) {

    Console.WriteLine("{0} | {1} | {2} | {3} | {4}", acr.IdentityReference.Value, acr.FileSystemRights, acr.InheritanceFlags, acr.PropagationFlags, acr.AccessControlType);

}

这给了我这行输出:


Everyone | Modify, Synchronize | ContainerInherit, ObjectInherit | None | Allow

因此,解决方案很简单(但如果您不知道要寻找什么,就很难正确解决!):


DirectorySecurity sec = Directory.GetAccessControl(path);

// Using this instead of the "Everyone" string means we work on non-English systems.

SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

Directory.SetAccessControl(path, sec);

这将使Windows安全对话框中的复选框与您已为测试目录设置的复选框匹配。


查看完整回答
反对 回复 2019-12-27
?
杨魅力

TA贡献1811条经验 获得超5个赞

使用FileSystemRights.FullControl替代FileSystemRights.Modify,如果你想允许所有操作(ACL)。


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 241 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信