Lefteris Gkinis
Lefteris Gkinis

Reputation: 1259

I Can't Read registry values from a service

Within my service i have the following function in order to take some values from my registry:

 Public Function GetKeyValue(ByVal nKey As String, ByVal sPath As String) As String
        Dim RegKey As RegistryKey
        Dim kValue As String = Nothing
        Dim Pos As String
        If CheckRegistry(sPath) Then
            Try
                RegKey = Registry.CurrentUser.OpenSubKey(sPath)
                kValue = CStr(RegKey.GetValue(nKey))

            Catch ex As Exception
                StartLogFile(" GetKeyValue " & vbNewLine & "Stack Trace= " & ex.StackTrace, EventLogEntryType.Warning)
            End Try
        End If
        Return kValue
    End Function

the same function works fine within a Windows form, but if i call from a service then she can't read the value. Is there anybody how knows what is going on?

Upvotes: 5

Views: 7675

Answers (4)

Francisco  Duarte
Francisco Duarte

Reputation: 71

Try not to access the registry key CurrentUser from windows services, I solved the same problem using LocalMachine key and OpenBaseKey method

RegistryKey rb =
    RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey rb2 = rb.OpenSubKey(@"[KEYPATH]");

Only replace KEYPATH to your path key.

Check it in: MSDN.

Upvotes: 1

gsharp
gsharp

Reputation: 27937

You should not store your data in HKEY_CURRENT_USER but under HKEY_LOCAL_MACHINE that makes more sense for a Windows-Service.

Be also aware that you can also set Permissions on Registry Keys. Check also that when try reading.

Upvotes: 5

Daniel A. White
Daniel A. White

Reputation: 190956

Is your service running as the same user as the Windows Forms application? If not, set it to run as the same user.

You will have to store it as CurrentMachine.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613192

You are almost surely reading registry settings of a different user. The service likely runs as one of the built-in service user accounts: SYSTEM, LOCALSERVICE or NETWORKSERVICE. These are not interactive users.

Your design is fundamentally flawed and I suspect you will need to move these settings into a file which is not part of a user profile.

Upvotes: 3

Related Questions