Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RegistryKey.SetValue

Tags:

c#

registrykey

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();
like image 916
kashif Avatar asked Jan 25 '13 22:01

kashif


People also ask

How do I read registry values?

Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.

How to Set value in Registry in c#?

string[] strings = {"One", "Two", "Three"}; Registry. SetValue(keyName, "TestArray", strings); // Your default value is returned if the name/value pair // does not exist. string noSuch = (string) Registry. GetValue(keyName, "NoSuchName", "Return this default if NoSuchName does not exist."); Console.

What does Reg_sz mean?

REG_SZ. A null-terminated string. This will be either a Unicode or an ANSI string, depending on whether you use the Unicode or ANSI functions.


1 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);
like image 175
Jon Avatar answered Sep 27 '22 22:09

Jon