Search code examples
c#.netregistry

Attempting to delete registry keys with subkeys results in an error


When I try to delete a key in HKCU that has subkeys I get an error.

Here is the code I am using:

using (RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"Software\Policies\", true))
{
   if (regkey.OpenSubKey("Google") != null)
   {
      regkey.DeleteSubKey("Google");
   }
}

The error I get:

Registry key has subkeys and recursive removes are not supported by this method.

How can I overcome it?


Solution

  • Use the RegistryKey.DeleteSubKeyTree method.

    RegistryKey.DeleteSubKeyTree Method (String)

    Deletes a subkey and any child subkeys recursively.

    using(RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"Software\Policies\", true))
    {
        if (regkey.OpenSubKey("Google") != null)
        {
            regkey.DeleteSubKeyTree("Google");
        }
    }