C#& Windows 10更改HKLM中密钥的注册表访问规则

时间:2017-01-03 16:30:07

标签: c# registry

有人可以帮助我 - 我开发了一个控制台应用程序,用于在HKLM中创建我自己的注册表项,然后修改对此键的访问权限,以便允许每个用户NT帐户能够读取/写入此键

在app.manifest中我有这个声明强制管理员权限运行它:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

在Windows 7 64位上一切正常,在Windows 10 64位上检测到问题 - 应用程序正在按预期创建注册表项,但是当它尝试修改其访问规则时,它会失败。

我修改密钥访问规则的代码:

private static bool SetFullAccessForKey(string regKey)
{
    try
    {
        SecurityIdentifier sid = new     SecurityIdentifier(WellKnownSidType.WorldSid, null);
        NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;

        using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(regKey, RegistryKeyPermissionCheck.ReadWriteSubTree))
        {
            RegistrySecurity rs = rk.GetAccessControl();

            RegistryAccessRule rar = new RegistryAccessRule(
               account.ToString(),
               RegistryRights.FullControl,
               InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
               PropagationFlags.None,
               AccessControlType.Allow);

            rs.AddAccessRule(rar);
            rk.SetAccessControl(rs);
        }
            return true;
        }
        catch
        {
            return false;
        }
}

有人可以帮助我,这里可能有什么不对吗? 正如我所说,在Windows 7 64上,一切都按预期工作。

感谢您的帮助!

EDITED 04-01-2017:关于执行SetFullAccessForKey(...)时我得到的异常的更多细节:

System.InvalidOperationException: This access control list is not in canonical form and therefore cannot be modified.
at System.Security.AccessControl.CommonAcl.ThrowIfNotCanonical()
at System.Security.AccessControl.CommonAcl.AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, Int32 accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
at System.Security.AccessControl.DiscretionaryAcl.AddAccess(AccessControlType accessType, SecurityIdentifier sid, Int32 accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
at System.Security.AccessControl.CommonObjectSecurity.ModifyAccess(AccessControlModification modification, AccessRule rule, Boolean& modified)
at System.Security.AccessControl.CommonObjectSecurity.AddAccessRule(AccessRule rule)
at System.Security.AccessControl.RegistrySecurity.AddAccessRule(RegistryAccessRule rule)
at regconfigtest.RegistryTools.SetFullAccessForKey(String regKey)

感谢您对此提供任何帮助!

1 个答案:

答案 0 :(得分:0)

我可以确认这里提出的解决方案:

How do you programmatically fix a non-canonical ACL?

解决了我的问题!现在它适用于所有:Win7,Win8和Win10。