Not getting internet settings windows registry value while running as a service

James J 606 Reputation points
2021-04-29T17:43:39.867+00:00

Hi,

We have one utility application which we need to get the "ProxyOverride" value from HKEY_CURRENT_USER internet settings. When I run the code from desktop application. I am able to get the value from the following windows registry.

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings

But, When I run the application as a service then application is looking into the below windows registry
HKEY_USERS.DEFAULT\Software\Microsoft\Windows\CurrentVersion\Internet Settings

Find the below code snippet for your reference.
const string Subkey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\";
string bypassProxyValue = string.Empty;
using (RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default).OpenSubKey(Subkey))
{
string[] keys = regKey.GetValueNames();
bypassProxyValue = regKey.GetValue("ProxyOverride").ToString();
}

Above code is perfectly working when we run from desktop and the same code is not working when we run as a service. Appreciate your quick help.

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,542 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 49,301 Reputation points
    2021-04-29T18:16:29.84+00:00

    Registry access from a windows service should not use HKCU. Refer to the discussion of HKCU at predefined-keys. Note that it says "This handle should not be used in a service or an application that impersonates different users. Instead, call the RegOpenCurrentUser function.
    For more information, see HKEY_CURRENT_USER."

    My understanding here is that your service would need to impersonate the user for which the information is desired and then call the RegOpenCurrentUser function so that the thread's token will be used thus avoiding the return of default values.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.