Search code examples
c#windowsserviceregistry

Registry.CurrentUser.OpenSubKey returns HKEY_USER key


In my Windows 7 test machine I have a registry key 'MyApp', which is visible under HKEY_CURRENT_USER\Software.

There is also key called 'S-1-5-21-xxxx-1000' under HKEY_USERS, with subkey 'Software' for the logged on user.

The 'MyApp' key is retrieved by a Windows Service which uses a LocalSystem account.

Issue 1 In theory HKEY_CURRENT_USER should reflect the HKEY_USERS entry. However, 'MyApp' is not visible under 'S-1-5-21-xxxx-1000\Software'. But it gets creepier...

Issue 2 The following C# code returns 'null', because it does not retrieve the key from HKEY_CURRENT_USER, but HKEY_USERS (S-1-5-21-xxxx-1000):

var myAppKey = Registry.CurrentUser.OpenSubKey(@"Software\MyApp");

(I know it is from HKEY_USERS (S-1-5-21-xxxx-1000), because when opening subkey 'Software' it does return a key, but with the subkeys from HKEY_USERS (S-1-5-21-xxxx-1000) in stead of HKEY_CURRENT_USER)

Now I must have overlooked something incredibly stupid, or my Windows 7 test machine is FUBAR.

I did my development on a Windows 10 machine, where the Windows Service is working fine.

Please help!


Solution

  • Thanks for the quick replies guys! I figured this one out. Turns out that running the service as a LocalSystem account on Windows 7 is the cause for the behaviour.

    In stead of returning the registry keys for HKEY_CURRENT_USER (the logged on user), Registry.CurrentUser will return HKEY_USERS.DEFAULT (again: on Windows 7).

    So, as a workaround, on Windows 7 I save/retrieve the settings to/from HKEY_LOCAL_MACHINE and all is good 😊!