Registry.LocalMachine.OpenSubKey() returns null

July 01, 2013 by Anuraj

.Net .Net 3.0 / 3.5 .Net 4.0

To verify excel installed on my local system; initially I tried using OpenSubKey() method. But it was always returning null, even though I can see the registry key using regedit.exe. I was using a Windows 8, x64 bit OS and the application was developed in VS 2008, Winforms, x86 platform. Later I found the reason - A 32-bit application on a 64-bit OS will be looking at the HKLM\Software\Wow6432Node node by default. To read the 64-bit version of the key, you’ll need to specify the RegistryView enumeration using OpenBaseKey() method.(This API is added in .Net 4.0.) And if you are using .Net 3.5 or below, either you need to build the application using Any CPU or x64 platform target.

var key = @"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot\";
using (var localMachine = RegistryKey.OpenBaseKey
    (RegistryHive.LocalMachine, RegistryView.Registry64))
using (var installRoot = localMachine.OpenSubKey(key, false))
{
    if (installRoot == null)
    {
        //Do something with installRoot
    }
}

Happy Programming.

You can find more details about RegistryKey.OpenBaseKey() method and RegistryView Enumeration in MSDN.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub