Skip to content

Instantly share code, notes, and snippets.

@hnuzhoulin
Last active December 1, 2016 10:49
Show Gist options
  • Save hnuzhoulin/3dcd158d021889b06ca7bc92ba4ed2a9 to your computer and use it in GitHub Desktop.
Save hnuzhoulin/3dcd158d021889b06ca7bc92ba4ed2a9 to your computer and use it in GitHub Desktop.
setting NTFS folder permission
using System;
using System.Collections;
using System.IO;
using System.Security.AccessControl;
static class Tester
{
public static void Main()
{
try
{
string filename = @"c:\dddd\test1"; //目标目录
string account = @"[email protected]";//用户名
string userrights = @"RW";//权限字符串,自己定义的
AddDirectorySecurity(filename, account, userrights);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
static public void AddDirectorySecurity(string FileName, string Account, string UserRights)
{
FileSystemRights Rights = new FileSystemRights();
if (UserRights.IndexOf("R") >= 0)
{
Console.WriteLine("R" + UserRights.IndexOf("R"));
Rights = Rights | FileSystemRights.Read;
}
if (UserRights.IndexOf("C") >= 0)
{
Console.WriteLine("C" + UserRights.IndexOf("C"));
Rights = Rights | FileSystemRights.ChangePermissions;
}
if (UserRights.IndexOf("F") >= 0)
{
Console.WriteLine("F" + UserRights.IndexOf("F"));
Rights = Rights | FileSystemRights.FullControl;
}
if (UserRights.IndexOf("W") >= 0)
{
Console.WriteLine("W" + UserRights.IndexOf("W"));
Rights = Rights | FileSystemRights.Write;
}
//Rights = Rights | FileSystemRights.Delete;
bool ok;
DirectoryInfo dInfo = new DirectoryInfo(FileName);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
//获取用于确定子对象如何继承此规则的标志的值
InheritanceFlags inherFlags = new InheritanceFlags();
inherFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
//获取传播标志的值,该值确定如何将此规则的继承传播到子对象
PropagationFlags propagationFlags = new PropagationFlags();
propagationFlags = PropagationFlags.InheritOnly;
//由propagationFlags和inherFlags两个值的组合来决定权限中的 “应用于” 属性,
FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, inherFlags, propagationFlags, AccessControlType.Allow);
dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);
dInfo.SetAccessControl(dSecurity);
//列出目标目录所具有的权限
DirectorySecurity sec = Directory.GetAccessControl(FileName, AccessControlSections.All);
foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
Console.WriteLine("----------------------------------");
Console.WriteLine(rule.IdentityReference.Value);
if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
{
Console.WriteLine(rule.FileSystemRights.ToString());
Console.WriteLine(rule.InheritanceFlags.ToString());
Console.WriteLine(rule.PropagationFlags.ToString());
}
} Console.Read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment