public static void SetDACL(string filePath, string userName)
{
//获取帐户信息
int cbSid = 100;
byte[] userSid = new byte[28];
StringBuilder domainName = new StringBuilder(255);
int domainNameLength = 255;
int sidType = 255;
bool result = LookupAccountName(null, userName, userSid, ref cbSid, domainName, ref domainNameLength, ref sidType);
if (!result)
return;
//获取文件描述符
ManagementPath path = new ManagementPath();
path.Server = ".";
path.NamespacePath = @"\root\cimv2";
path.RelativePath = @"Win32_LogicalFileSecuritySetting.Path='" + filePath + "'";
ManagementObject dir = new ManagementObject(path);
ManagementBaseObject outParams = dir.InvokeMethod("GetSecurityDescriptor", null, null);
if (((uint)(outParams.Properties["ReturnValue"].Value)) != 0)
{
throw new Exception("获取文件描述符失败");
}
ManagementBaseObject Descriptor = ((ManagementBaseObject)(outParams.Properties["Descriptor"].Value));
//获取访问控制列表
ManagementBaseObject[] DaclObject = ((ManagementBaseObject[])(Descriptor.Properties["Dacl"].Value));
//复制一个访问控制项
ManagementBaseObject ace = (ManagementBaseObject)DaclObject[0].Clone();
//设置访问控制项属性
ManagementBaseObject trustee = (ManagementBaseObject)ace.Properties["Trustee"].Value;
// return ace.Properties["AccessMask"].Value.ToString();
trustee.Properties["Domain"].Value = domainName.ToString();
trustee.Properties["Name"].Value = userName;
trustee.Properties["SID"].Value = userSid;
trustee.Properties["SidLength"].Value = 28;//trustee.Properties["SIDString"].Value="S-1-5-21-602162358-708899826-854245398-1005";
ace.Properties["Trustee"].Value = trustee;
ace.Properties["AccessMask"].Value = 1245631;//2032127完全控制//1245631修改权限
ace.Properties["AceFlags"].Value = 3;//允许AccessMask指定的访问级别
ace.Properties["AceType"].Value = 0;//允许AccessMask指定的访问级别
//复制一份访问控制列表,并将以上生成的访问控制项添加到其后。
ManagementBaseObject[] newDacl = new ManagementBaseObject[DaclObject.Length + 1];
for (int i = 0; i < DaclObject.Length; i++)
{
newDacl[i] = DaclObject[i];
}
newDacl[DaclObject.Length] = ace;
//将安全描述符的DACL属性设为新生成的访问控制列表
Descriptor.Properties["Dacl"].Value = newDacl;
//设置安全描述符
dir.Scope.Options.EnablePrivileges = true;
ManagementBaseObject inProperties = dir.GetMethodParameters("SetSecurityDescriptor");
inProperties["Descriptor"] = Descriptor;
outParams = dir.InvokeMethod("SetSecurityDescriptor", inProperties, null);
}