/// <summary> /// Set registry permissions on a registry key for a specified account. /// </summary> public static bool SetRegPermission(RegistryKey rootKey, string subKeyPath, string account, RegistryRights rights) { bool result = false; RegistryAccessRule accessRule = new RegistryAccessRule(account, rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); using (RegistryKey key = rootKey.OpenSubKey(subKeyPath, true)) { RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access); keySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (result) { accessRule = new RegistryAccessRule(account, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); keySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (result) { key.SetAccessControl(keySecurity); } } } return(result); }
static void Modify() { try { //Registry.LocalMachine.CreateSubKey( @"SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.None, RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", false); RegistrySecurity resSec = regKey.GetAccessControl(); AuthorizationRuleCollection authRules = resSec.GetAccessRules(true, true, typeof(NTAccount)); foreach (RegistryAccessRule rule in authRules) { if (rule.IdentityReference.Value == "TW\\0007989") { if (rule.RegistryRights != RegistryRights.FullControl) { // Set full RegistryAccessRule newRule = new RegistryAccessRule(rule.IdentityReference, RegistryRights.FullControl, AccessControlType.Allow); bool isModified = false; if (resSec.ModifyAccessRule(AccessControlModification.Add, newRule, out isModified) == false) { Console.WriteLine("Modify access rule failed"); } } } } regKey.Close(); } catch (Exception exp) { string s = exp.ToString(); } }