NullReferenceException when opening a subkey I know exists

南楼画角 提交于 2019-11-28 14:35:35

You're most likely experiencing what's called Registry Redirection.

To maintain compatibility with 32-bit applications, 64-bit versions of Windows implemented the File System Redirector and the Registry Redirector. The purpose of these two is to keep a seperate set of files and registry keys (usually goes under the name WOW64) that are specific to 32-bit applications only.

For instance, due to that a 64-bit process cannot load 32-bit code, a separate system directory is kept with only 32-bit versions of the system DLLs and applications. The path to the 32-bit system directory is %SystemRoot%\SysWOW64, while the 64-bit directory is the standard %SystemRoot%\System32.

This works the same way in the registry, though only a certain set of keys have a respective 32-bit key. The 32-bit key is always located as a subkey of the standard 64-bit key (for example HKLM\SOFTWARE) and is called Wow6432Node.

The File System Redirector (and respectively the Registry Redirector) automatically redirects all 32-bit apps to the respective 32-bit directory/registry key to ensure that 32-bit apps still work on 64-bit systems. By default Visual Studio projects target 32-bit only.

As far as I know there are two ways to overcome this problem:

  1. Compile your app as AnyCPU instead of x86.

    This is by far the most simple solution. By doing this the app will automatically run as a 32-bit app on a 32-bit system, or as a 64-bit app on a 64-bit system. Thus the Registry Redirector won't need to intervene.

  2. Specify if you want to access the 32-bit view or the 64-bit view of the registry.

    The .NET Framework has a built in feature that lets you specify if you want to access the 32-bit view or the 64-bit view of the registry. Combine that with Environment.Is64BitOperatingSystem to determine which view you want to access.

    Local solution (for others seeing this):

    'Determine which registry view to use.
    Dim RegView As RegistryView = If(Environment.Is64BitOperatingSystem, RegistryView.Registry64, RegistryView.Registry32)
    
    'Opens HKEY_LOCAL_MACHINE with the specified registry view.
    Using RegHive As RegistryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegView)
    
        'Open the "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileGuid" key.
        Using RegKey As RegistryKey = RegHive.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileGuid", True)
            'Do stuff with the registry key...
        End Using
    End Using
    

    Remote solution:

    (same as above, but changed the Using RegHive As RegistryKey line)

    Using RegHive As RegistryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, host.txt, RegView)
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!