2

I am trying to read a registry key from a Windows server, and I can't seem to get it to work either with or without leading slashes. If I try:

lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "\\SOFTWARE\\Company\\Product\\ServerName", 0, KEY_QUERY_VALUE, &hDomainKey);

It gives me error 161, which is ERROR_BAD_PATHNAME. (The specified path is invalid.)

Okay, so trying it this way:

lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Company\\Product\\ServerName", 0, KEY_QUERY_VALUE, &hDomainKey);

I get error 2, ERROR_FILE_NOT_FOUND. (The system cannot find the file specified.)

I can open regedit and see the value I want to retrieve, with path My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Company\Product, name ServerName, and type REG_SZ. What am I missing here?

hmjd
  • 120,187
  • 20
  • 207
  • 252
Joe M
  • 3,060
  • 3
  • 40
  • 63

1 Answers1

8

Open the key, not the value:

lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                      "SOFTWARE\\Company\\Product",
                      0,
                      KEY_QUERY_VALUE,
                      &hDomainKey);

and then read the value using RegQueryValueEx() (or RegGetValue()).

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 1
    +1. Note that RegGetValue works on Vista and later only. Consider `RegQueryValue` or `RegQueryValueEx` if you need to support earlier than that -- but watch out for null termination problems. – Billy ONeal Dec 10 '12 at 20:56
  • Zoinks! I have `RegQueryValueEx` following the code I posted, but I misunderstood the relationship between the two calls. Thanks. I'll accept this in a few minutes when the time limit elapses. – Joe M Dec 10 '12 at 21:00