Search code examples
c#registry

Registry Value Access


I have been trying to work out why I can not access a value in the registry. I ended up with a possible solution but I would like to know why one works and the other doesn't and if I can go ahead and use this solution.

The original code:

RegistryKey regKey1 = Registry.LocalMachine.OpenSubKey(regPath);
string regValue1 = (string)regKey1.GetValue("CodeBase");

This fails because regKey1 is null.

A possible replacement (this works):

string regValue2 = (string)Registry.GetValue(Registry.LocalMachine.Name + regPath, "CodeBase", String.Empty);

According to this post there should be a different way of accessing the registry if the program is compiled for 32-bit and is running on a 64-bit machine. I am using a 64-bit version of Windows 7 and the program is being compiled for 'Any CPU'. However, if this was the reason then I would expect both solutions above to fail.

Can someone please explain the difference?

EDIT:

Found the problem.

regPath = @"\SOFTWARE\Wow6432Node\Classes\CLSID\ ...";

Because of the comment by David Heffernan I changed Registry.LocalMachine.Name + regPath into Path.Combine(Registry.LocalMachine.Name, regPath), but this didn't work to start with because regPath started with a '\' (the items were not combined - without an exception). Then I realized that OpenSubKey() also doesn't like the '\' at the start. After removing this from regPath both versions work the same. Thanks David and thanks also for your suggestions about using the RegistryView enum.


Solution

  • Version 1

    If the key does not exist then regKey1 is null, and the call to regKey1.GetValue() fails for the obvious reason.

    Version 2

    If the key does not exist, Registry.GetValue() returns null, and regValue1 is therefore assigned null.


    Regarding the issue of registry views and AnyCPU, you are asking for trouble at present. Presumably you mean to look in a specific registry view. You should be explicit about this by using the RegistryView enumeration.