44

I have a registry path of the following

HKEY_LOCAL_MACHINE\SOFTWARE\COMPANY\COMPFOLDER

inside COMPFOLDER, I have a string value called "Deno" whose value is 0. I wish to change its value to 1 by code whenever I execute the code. Can anyone help me?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Harish Kumar
  • 2,015
  • 4
  • 18
  • 18
  • 4
    How did the value *get* in that registry key in the first place? I assume that you used the [`Microsoft.Win32.Registry`](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx) class to write it, so you should use the same class to *modify* it. What problems did you have when you tried to do this? – Cody Gray - on strike Jan 11 '12 at 08:21
  • I'd assume that he navigated to the registry, copied the path and is desirous of creating a program to make changes to it through code.. Just a guess but that's how I got here. I appreciate your answer Cody Gray. It answered my question in part. – iDevJunkie Jan 15 '15 at 07:22
  • Use the Registry class as described here. http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx – agarcian Jan 11 '12 at 08:23

2 Answers2

67

It's been a while I did reg hacks, but something like this could work:

RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Company\\Compfolder", true);
if(myKey != null)    {
   myKey.SetValue("Deno", "1", RegistryValueKind.String);
   myKey.Close();
}
Jontatas
  • 954
  • 7
  • 17
  • 3
    `myKey` should be in a `using` statement. See the [remarks for `RegistryKey`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey?view=netframework-4.8#remarks) – Liam May 01 '19 at 12:34
  • 1
    Since the key I had to modify started with HKCU, I replaced "Registry.LocalMachine." with "Registry.CurrentUser." and it worked all right. Thank you! – MundoPeter Feb 12 '21 at 15:36
21
using (RegistryKey key = regKeyRoot.OpenSubKey(KeyName, true)) // Must dispose key or use "using" keyword
{
    if (key != null)  // Must check for null key
    {
        key.SetValue(attribute, value);
    }
}
Yoshi Askharoun
  • 101
  • 3
  • 13
electricalbah
  • 2,227
  • 2
  • 22
  • 36