Reputation: 8699
I have SQL Server installed.
In the registry, the key MSSQLServer at *HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft* looks like this:
All of the following lines of code return values from the registry:
var mainKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("MSSQLServer");
var subKey1 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("MSSQLServer").OpenSubKey("Client");
var subKey2 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("MSSQLServer").OpenSubKey("MSSQLServer").OpenSubKey("CurrentVersion");
However, this one does not:
var subKey3 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("MSSQLServer").OpenSubKey("Setup");
"Setup" looks to be the same type of value as the other keys. Any thoughts why this command returns null?
Upvotes: 5
Views: 7116
Reputation: 40838
Your application is 32-bit and that is a 64-bit registry key. 32-bit and 64-bit applications have different views of the registry. In regedit the key you are getting in code is at HKLM\Software\Wow6432Node\MSSQLServer, not HKLM\Software\MSSQLServer (in your picture).
Unfortunately, the managed API for accessing registry keys does not allow a 32-bit application to get a 64-bit view of the registry.
There are two options: Change your application to target AnyCPU or x64 or P/Invoke the unmanaged API. This has an example of how to do the P/Invoke and the MSDN documentation.
BTW, you can pass a path to the OpenSubKey method instead of chaining them together like that.
Update: I was not quite correct above. As of .NET 4, the OpenBaseKey
method (MSDN) can be used to get a 64-bit view in a 32-bit application.
Upvotes: 12