Frage

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

Cannot write to the registry key.

Where am I going 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();
War es hilfreich?

Lösung

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);

Andere Tipps

You don't need the rs part unless you are trying to assign specific permissions to the key you are creating.

You need to:

  1. Open the key where you want to create your subkey and assign it to a RegistryKey variable. Add a true Boolean to mark it as writeable.
  2. Create your subkey using that variable, and assign that back to the same variable.
  3. Set the value using your RegistryKey variable.

Example:

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

If you just want to edit an existing key, as System is, you don't use CreateSubKey, because the key already exists. That is only for creating new keys. You use OpenSubKey.

RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
key.SetValue("kashif", 1, RegistryValueKind.DWord);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top