给文件夹添加用户权限(转)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值