How to use RegistryKey.SetValue

I am trying to create a new registry key using the following code and getting this error:

Cannot write to the registry key.

Where am I wrong ???

var rs = new RegistrySecurity();
string user = Environment.UserDomainName + "\\" + Environment.UserName;
rs.AddAccessRule(new RegistryAccessRule(user,
                                        RegistryRights.WriteKey | RegistryRights.SetValue,
                                        InheritanceFlags.None,
                                        PropagationFlags.None,
                                        AccessControlType.Allow));
RegistryKey key;
key = Registry.LocalMachine.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", RegistryKeyPermissionCheck.ReadSubTree, rs);
key.SetValue("kashif", 1, RegistryValueKind.DWord);
key.Close();
+5
source share
2 answers

You need to open the newly created key for read / write access:

key = Registry.LocalMachine.CreateSubKey(
    @"Software\Microsoft\Windows\CurrentVersion\Policies\System",
    RegistryKeyPermissionCheck.ReadWriteSubTree, // read-write access
    rs);
+7
source

You do not need a part rsif you are not trying to assign specific rights to the generated key.

You need:

  • Open the key in which you want to create your subsection, and assign it to a variable RegistryKey. Add a trueBoolean to mark it as writable.
  • Create your subsection using this variable and assign it back to the same variable.
  • Set the value using a variable RegistryKey.

Example:

RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
key = key.CreateSubKey("MyNewKey");
key.SetValue("kashif", 1, RegistryValueKind.DWord);

, System is, CreateSubKey, . . OpenSubKey.

RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
key.SetValue("kashif", 1, RegistryValueKind.DWord);
0

All Articles