Search code examples
c#registry

Will disposing a RegistryKey also close it?


As the title says.

Also, the other way around; will closing a RegistryKey dispose it?

I've looked around in all documentation I could find and nothing of this is mentioned anywhere.


Solution

  • It will call the Dispose() method inside of Close(), meaning YES it will be "disposed" and other way around Dispose() will Close() key. System registry keys are never closed. Only keys that are being closed - HKEY_PERFORMANCE_DATA.

    .NET source for Close method:

    /**
     * Closes this key, flushes it to disk if the contents have been modified.
     */
    public void Close() {
        Dispose(true);
    }
    

    .NET source line 220

    .NET source for Dispose method:

    [System.Security.SecuritySafeCritical]  // auto-generated
    private void Dispose(bool disposing) {
          if (hkey != null) {
               if (!IsSystemKey()) {
                  try {
                      hkey.Dispose();
                    }
                    catch (IOException){
                        // we don't really care if the handle is invalid at this point
                    }
                    finally
                    {
                        hkey = null;
                    }
                }
                else if (disposing && IsPerfDataKey()) {
                SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
                }  
          }
    }
    

    .NET source line 227