How to use RegistryKey.SetValue

kashif picture kashif · Jan 25, 2013 · Viewed 17.1k times · Source

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

Answer

Jon picture Jon · Jan 25, 2013

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