且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

新增]每个人都"特权使用C#.NET到文件夹

更新时间:2023-02-05 12:32:15

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

First thing I want to tell you is how I found this solution. This is probably more important than the answer because file permissions are hard to get correct.

第一件事情是我设置使用Windows对话框和复选框想要的权限。我增加了对所有人的规则和除完全控制选中所有框。

First thing I did was set the permissions I wanted using the Windows dialogs and checkboxes. I added a rule for "Everyone" and ticked all boxes except "Full Control".

然后我写了这个C#code告诉我,正是我的参数需要复制Windows设置:

Then I wrote this C# code to tell me exactly what parameters I need to duplicate the Windows settings:

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

这给了我这个行输出的:

This gave me this line of output:

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

因此​​,解决办法很简单(但很难,如果你不知道该怎么找得到吧!)

So the solution is simple (yet hard to get right if you don't know what to look for!):

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安全对话框匹配。

This will make the checkboxes on the Windows security dialog match what you have already set for your test directory.