Search code examples
c#registryregistrykey

Delete a Registry key using C#


I am trying to delete a Registry key like this:

RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(
    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts", true);

oRegistryKey.DeleteSubKeyTree(".");

But that is giving me an exception:

Cannot delete a subkey tree because the subkey does not exist

If I change DeleteSubKeyTree to DeleteSubKey, I receive a different exception:

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


Solution

  • Try this:

    string str = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts";
    string[] strSplit = strLocal.Split('\\');
                using (RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts", true))
                {
                    RegistryKey hdr = oRegistryKey.OpenSubKey(strSplit[strSplit.Length-2], true);
                    foreach (String key in hdr.GetSubKeyNames())
                        hdr.DeleteSubKey(key);
                    hdr.Close();
                    oRegistryKey.DeleteSubKeyTree(strSplit[strSplit.Length - 2]);
                }
    

    Also check: Registry in .NET: DeleteSubKeyTree says the subkey does not exists, but hey, it does!