user2061745
user2061745

Reputation: 305

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?

Upvotes: 12

Views: 10418

Answers (2)

GooliveR
GooliveR

Reputation: 244

using(var regkey = Registry.CurrentUser.OpenSubKey(@"Software\Policies\", true))
{
   regkey?.DeleteSubKeyTree("Google");
}

Upvotes: 1

Jason Watkins
Jason Watkins

Reputation: 3785

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");
    }
}

Upvotes: 28

Related Questions