Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add key to registry if not exist

Tags:

c#

registry

I try to add a key to the registry if not exist. While I debug everything is fine. Code should work. But I can't find key in registry editor. Do you have any idea?

public void ConfigureWindowsRegistry()
{
    var reg = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\Outlook\\FormRegions\\tesssst", true);
    if (reg == null)
    {
        reg = Registry.LocalMachine.CreateSubKey("Software\\Microsoft\\Office\\Outlook\\FormRegions\\tesssst");
    }

    if (reg.GetValue("someKey") == null)
    {
            reg.SetValue("someKey", "someValue");
    }
}
like image 748
Raskolnikov Avatar asked Mar 20 '15 10:03

Raskolnikov


1 Answers

If you are using a 64bit OS some registry keys are redirected by WOW64. More information on this topic is available on MSDN , you should look under Wow6432Node and you will find your entry. If you execute that code the first time it will create, on a 64 bit machine (I tried it locally), this entry:

HKEY_LOCAL_MACHINE\Software\Wow6432Node \Microsoft\Office\Outlook\FormRegions\tesssst

if you want to access your 64 bit section of the registry you should do:

public void ConfigureWindowsRegistry()
{
    RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); //here you specify where exactly you want your entry

   var reg = localMachine.OpenSubKey("Software\\Microsoft\\Office\\Outlook\\FormRegions\\tesssst",true);
   if (reg == null)
   {
       reg = localMachine.CreateSubKey("Software\\Microsoft\\Office\\Outlook\\FormRegions\\tesssst");
   }

   if (reg.GetValue("someKey") == null)
   {
       reg.SetValue("someKey", "someValue");
   }
}

Executing the code above will put the registry key in the correct section you are targeting.

hope it helps.

like image 120
codingadventures Avatar answered Oct 04 '22 04:10

codingadventures