I'm currently having an issue when writing an app to set permissions on some Legacy keys. Legacy keys are quite locked down and to actually modify them in regedit you have to take ownership and then add yourself with full control. When trying to replicate this in code i cannot get the key for write with the error "Access is denied". Example code:
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Allow));
rs.SetOwner(new NTAccount("Administrators"));
return LocalMachine.CreateSubKey(post, RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
Any ideas would be greatly appreciated. I have also tried OpenSubKey with write access requested and I just cannot get the key.
Thanks guys.
I finally found a solution. You had to open the key with "ChangePermissions" and then change the permission for yourself... THEN re-open the key with full control to change the owner. Here's how.
RegistryKey rk = LocalMachine.OpenSubKey(subkey, RegistryKeyPremissionsCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey);//Get the registry key desired with ChangePermissions Rights.
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule("Administrator", RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));//Create access rule giving full control to the Administrator user.
rk.SetAccessControl(rs); //Apply the new access rule to this Registry Key.
rk = LocalMachine.OpenSubKey(subkey, RegistryKeyPremissionsCheck.ReadWriteSubTree, RegistryRights.FullControl); // Opens the key again with full control.
rs.SetOwner(new NTAccount("Administrator"));// Set the securitys owner to be Administrator
rk.SetAccessControl(rs);// Set the key with the changed permission so Administrator is now owner.
This works for me. Let me know if it works for you :)
Obviously change Administrator to another user if you aren't logged in as administrator or if you need rights for another user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With