Sur*_*ary 69 c# directory-security access-rights
我使用下面的代码允许Everyone访问文件夹:
System.Security.AccessControl.DirectorySecurity sec =
System.IO.Directory.GetAccessControl(directory, AccessControlSections.All);
FileSystemAccessRule accRule = new FileSystemAccessRule("Everyone",
FileSystemRights.Modify,
AccessControlType.Allow);
sec.AddAccessRule(accRule); // setACL
sec.ResetAccessRule(accRule);
Run Code Online (Sandbox Code Playgroud)
现在,Everyone用户已添加到该文件夹,但未分配任何权限.不检查所有读,写,执行等复选框.
Yos*_*shi 121
我想告诉你的第一件事是我是如何找到这个解决方案的.这可能比答案更重要,因为文件权限很难得到纠正.
我做的第一件事是使用Windows对话框和复选框设置我想要的权限.我为"Everyone"添加了一条规则,并勾选了除"完全控制"之外的所有框.
然后我写了这个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);
}
Run Code Online (Sandbox Code Playgroud)
这给了我这一行输出:
Everyone | Modify, Synchronize | ContainerInherit, ObjectInherit | None | Allow
Run Code Online (Sandbox Code Playgroud)
因此,解决方案很简单(如果您不知道要寻找什么,那么很难做到正确!):
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);
Run Code Online (Sandbox Code Playgroud)
这将使Windows安全性对话框上的复选框与您已为测试目录设置的复选框相匹配.
小智 12
string file = @"D:\Richi";
private static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47925 次 |
| 最近记录: |