Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempting to delete registry keys with subkeys results in an error

Tags:

c#

.net

registry

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?

like image 255
user2061745 Avatar asked Mar 25 '13 01:03

user2061745


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");
    }
}
like image 135
Jason Watkins Avatar answered Nov 11 '22 14:11

Jason Watkins


using(var regkey = Registry.CurrentUser.OpenSubKey(@"Software\Policies\", true))
{
   regkey?.DeleteSubKeyTree("Google");
}
like image 37
GooliveR Avatar answered Nov 11 '22 15:11

GooliveR