josibu josibu - 9 months ago 65
C# Question

C# Unable to load registry values in LocalMachine

I am writing an application that loads parameters from the registry. Here is the code I use to load it:

public bool getRegValues() //get values used for the SQL Connection etc
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))
if (key != null)
this.serverName = key.GetValue("SQLserver").ToString();
this.timeout = key.GetValue("timeout").ToString();
this.Database = key.GetValue("database").ToString();
this.logTable = key.GetValue("table_log").ToString();
this.budgetTable = key.GetValue("table_budget").ToString();
this.personsTable = key.GetValue("table_persons").ToString();
this.tempTable = key.GetValue("table_temp").ToString();
this.cashiersDB = key.GetValue("cashiersDB").ToString();
this.customersTbl = key.GetValue("cashiersCustomersTable").ToString();

key.SetValue("version", version);
if (this.serverName == null || this.timeout == null || this.Database == null || this.logTable == null
|| this.budgetTable == null || this.personsTable == null || this.tempTable == null)
Console.WriteLine("One of the values could not be loaded.");
return false;
Console.WriteLine("Key is null.");
return false;
return true;

When I run the code on my workstation everything is perfect. When I do it on the server it returns false and writes "Key is null.".

When I compile the code using Registry.CurrentUser instead of Registry.LocalMachine it returns true (Of course the values in the different locations are identical).

What is wrong? I am domain admin and have also given myself explicitly full control permissions to the Key HKEY_LOCAL_MACHINE\SOFTWARE\Company\Application\NightJob\

Any ideas?

Answer Source

If you are using .Net 4 try this using:

using(RegistryKey SoftwareKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))