public void SetupSubKeyPathAndAccessRights() { var pathArray = SubKey.Split('\\'); RegistryKey baseRegistryKey = BaseRegKeyCurrentUser; //string ssid = WindowsIdentityHelper.GetUniqueSecurityIdForCurrentUser(); WindowsIdentity windowsIdentity = WindowsIdentityHelper.GetWindowsIdentityForCurrentUser(); foreach (string path in pathArray) { RegistryKey sk1 = baseRegistryKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree); bool userAccessGranted = true; if (sk1 == null) { sk1 = baseRegistryKey.CreateSubKey(path); } if (sk1 == null) { userAccessGranted = false; } if (userAccessGranted) { continue; } var registrySecurity = new RegistrySecurity(); IdentityReference identityReference = new NTAccount(windowsIdentity.Name); var rule = new RegistryAccessRule(identityReference, RegistryRights.CreateSubKey | RegistryRights.ReadKey | RegistryRights.WriteKey, AccessControlType.Allow); registrySecurity.AddAccessRule(rule); sk1 = baseRegistryKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadSubTree); sk1?.SetAccessControl(registrySecurity); } }
void BackupCreateKeyTree(List <RegChange> rollbackRegistry) { char[] delim = { '/', '\\' }; string[] subKeys = SubKey.Split(delim, StringSplitOptions.RemoveEmptyEntries); string tempKey = ""; foreach (string t in subKeys) { tempKey += t + "\\"; if (!SubkeyExists(tempKey)) { //backup a "delete" key rollbackRegistry.Add(new RegChange(RegOperations.RemoveKey, RegBasekey, tempKey, Is32BitKey)); break; } } }
/// <summary> /// Adds subkey to registry key /// </summary> /// <returns>Registry key, or null if unable to be created</returns> public RegistryKey CreateSubKey() { RegistryKey regKey = null; if (string.Compare(RootKey, "HKEY_CLASSES_ROOT", StringComparison.Ordinal) == 0) { regKey = Registry.ClassesRoot; } else if (string.Compare(RootKey, "HKEY_CURRENT_USER", StringComparison.Ordinal) == 0) { regKey = Registry.CurrentUser; } else if (string.Compare(RootKey, "HKEY_LOCAL_MACHINE", StringComparison.Ordinal) == 0) { regKey = Registry.LocalMachine; } else if (string.Compare(RootKey, "HKEY_USERS", StringComparison.Ordinal) == 0) { regKey = Registry.Users; } else if (string.Compare(RootKey, "HKEY_CURRENT_CONFIG", StringComparison.Ordinal) == 0) { regKey = Registry.CurrentConfig; } if (string.IsNullOrEmpty(SubKey)) { return(regKey); } if (SubKey.IndexOf('\\') > 0) { foreach (var subKey in SubKey.Split('\\')) { try { regKey = regKey?.CreateSubKey(subKey); } catch (Exception ex) { Debug.WriteLine("Unable to create sub key ({0}) for registry path ({1}).\nError: {2}", subKey, RegistryKeyPath, ex.Message); regKey = null; } if (regKey == null) { break; } } } else { try { regKey = regKey?.CreateSubKey(SubKey); } catch (Exception ex) { Debug.WriteLine("Unable to create sub key ({0}) for registry path ({1}).\nError: {2}", SubKey, RegistryKeyPath, ex.Message); regKey = null; } } return(regKey); }