Attempting to delete registry keys using subkeys results in an error

When I try to remove a key from an HKCU that has children, I get an error.

Here is the code I'm using:

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

The error I get is:

The registry key has subkeys, and recursive deletes are not supported by this method.

How can I overcome it?

+7
source share
2 answers

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"); } } 
+19
source
 using(var regkey = Registry.CurrentUser.OpenSubKey(@"Software\Policies\", true)) { regkey?.DeleteSubKeyTree("Google"); } 
0
source

All Articles