Delete a Registry key using C#

Digvijay Rathore picture Digvijay Rathore · Aug 27, 2015 · Viewed 7.8k times · Source

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

Answer

DavidRR picture DavidRR · Jan 10, 2017

The approach outlined in this answer is needlessly complex because DeleteSubKeyTree is recursive. From its documentation on MSDN:

Deletes a subkey and any child subkeys recursively.

So, if your goal is to delete the user's FileExts key, do this:

string explorerKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Explorer";

using (RegistryKey explorerKey =
    Registry.CurrentUser.OpenSubKey(explorerKeyPath, writable: true))
{
    if (explorerKey != null)
    {
        explorerKey.DeleteSubKeyTree("FileExts");
    }
}

However, are you sure that you really want to delete a user's FileExts key? I believe that most would consider doing so would be unreasonably destructive and reckless. A more common scenario would be deleting a single file extension key (e.g., .hdr) from the FileExts key.

Finally, note that DeleteSubKeyTree is overloaded. Here is the signature of the second version of this method:

public void DeleteSubKeyTree(
    string subkey,
    bool throwOnMissingSubKey
)

With this version, if subkey does not exist and throwOnMissingSubKey is false, DeleteSubKeyTree will simply return without making any changes to the Registry.