// It's up to the caller to obtain the needed token privileges (TakeOwnership) for this operation public static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName) { using RegistryKey subKey = registryKey.OpenSubKeyOrThrowIfMissing(subkeyName, RegistryRights.TakeOwnership | RegistryRights.ChangePermissions ); RegistrySecurity accessRules = subKey.GetAccessControl(); accessRules.SetOwner(WindowsIdentity.GetCurrent().User); accessRules.ResetAccessRule( new RegistryAccessRule( WindowsIdentity.GetCurrent().User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow ) ); subKey.SetAccessControl(accessRules); }
public static void Main() { string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. RegistrySecurity mSec = new RegistrySecurity(); // Add a rule that grants the current user the right // to read and enumerate the name/value pairs in a key, // to read its access and audit rules, to enumerate // its subkeys, to create subkeys, and to delete the key. // The rule is inherited by all contained subkeys. // RegistryAccessRule rule = new RegistryAccessRule(user, RegistryRights.ReadKey | RegistryRights.WriteKey | RegistryRights.Delete, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); mSec.AddAccessRule(rule); // Add a rule that allows the current user the right // right to set the name/value pairs in a key. // This rule is inherited by contained subkeys, but // propagation flags limit it to immediate child // subkeys. rule = new RegistryAccessRule(user, RegistryRights.ChangePermissions, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit, AccessControlType.Allow); mSec.AddAccessRule(rule); // Add a rule that denies the current user the right // to set the name/value pairs in a key. This rule // has no inheritance or propagation flags, so it // affects only the key itself. rule = new RegistryAccessRule(user, RegistryRights.SetValue, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Create a rule that allows the current user // only read access to a key, with no inheritance // or propagation flags. ResetAccessRule removes // all the existing rules for the current user, // replacing them with this rule. rule = new RegistryAccessRule(user, RegistryRights.ReadKey, AccessControlType.Allow); mSec.ResetAccessRule(rule); // Display the rules in the security object. // removed. ShowSecurity(mSec); }