title: Checking if a registry key exists
body: <p>I am looking for a clean way to check if a registry key exists. I had assumed that <code>RegOpenKey</code> would fail if I tried to open a key that didn't exist, but it doesn't.</p>
  
  <p>I could use string processing to find and open the parent key of the one I'm looking for, and then enumerate the subkeys of that key to find out if the one I'm interested in exists, but that feels both like a performance hog and a weird way to have to implement such a simple function.</p>
  
  <p>I'd guess that you could use <code>RegQueryInfoKey</code> for this somehow, but MSDN doesn't give too many details on how, even if it's possible.</p>
  
  <p><strong>Update</strong>: I need the solution in Win32 api, not in managed code, .NET or using any other library.</p>
  
  <p>The docs in MSDN seem to indicate that you should be able to open a key for read permission and get an error if it doesn't exist, like this:</p>
  
  <pre><code>lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &amp;hKey);
  
  if (lResult != ERROR_SUCCESS) 
  {
      if (lResult == ERROR_FILE_NOT_FOUND) {
  </code></pre>
  
  <p>However, I get <code>ERROR_SUCCESS</code> when I try this.</p>
  
  <p><strong>Update 2</strong>: My exact code is this:</p>
  
  <pre><code>HKEY subKey = nullptr;
  LONG result = RegOpenKeyEx(key, subPath.c_str(), 0, KEY_READ, &amp;subKey);
  if (result != ERROR_SUCCESS) {
  </code></pre>
  
  <p>... but <code>result</code> is <code>ERROR_SUCCESS</code>, even though I'm trying to open a key that does not exist.</p>
  
  <p><strong>Update 3</strong>: It looks like you guys are right. This fails on one specific test example (mysteriously). If I try it on any other key, it returns the correct result. Double-checking it with the registry editor still does not show the key. Don't know what to make of all that.</p>