How to delete an entire Registry sub key tree using C#?


Registry is the heart of Windows Operating System and all/most of the apps and games associates various values/data into the registry, which can be accessed at different point of time. Playing with Windows registry is very dangerous and hence general people should avoid or take special care while working with it.

 

In case you are a developer, you want to read/write/delete entries to/fro Windows Registry. This post will cover details and code snippets to delete an entire key tree from it. Continue reading to learn how to do it.

 

How to delete an entire Registry key tree using C#? (www.kunal-chowdhury.com)

 

Microsoft .NET API provides an easy way to access the Windows Registry. You can read/write/delete any registry keys/values/data using C# or VB.NET code. The .NET framework provides a sealed class named RegistryKey present under Microsoft.Win32 namespace. This class provides an API named DeleteSubKeyTree, which when called deletes the specified subkey and any child subkeys recursively.

 

Here I have written an optimized helper class that will help you to do the job very easily. You need to pass the registry path (of type “RegistryKey”) and the key to delete (of type “string”). The code is self explanatory with comments wherever applicable.

public class RegistryHelper
{
    /// <summary>
    /// Deletes the specified key tree from the Windows Registry.
    /// </summary>
    /// <param name="registryPath">The registry path.</param>
    /// <param name="keyToDelete">The key to delete.</param>
    public static void DeleteSubKeyTree(RegistryKey registryPath, string keyToDelete)
    {
        if (registryPath != null && !string.IsNullOrWhiteSpace(keyToDelete))
        {
            // Set "throwOnMissingSubKey" to "true", if you want the system to throw exception 
            // when the given key is not found. In other case, set it to "false".
            bool throwOnMissingSubKey = false;
            try { registryPath.DeleteSubKeyTree(keyToDelete, throwOnMissingSubKey); }
            catch
            {
                // Handle the exception, if any.
            }
        }
    }
}

 

If you want to throw an exception when the specified key is not found, set the throwOnMissingSubKey to “true”. If you set it as “false”, it will just skip the call when no key specified by that name is found. To call the method, first create the registry key path where the specified key is available and then call that helper method passing the registry path and the key to delete.

 

Here’s a sample code which shows you how to call that method. Make sure that, you selected the proper registry root and the correct path before calling this method.

/* 
 * WARNING: Playing with system registry is dangerous. It may corrupt your system.
 * Take precaution while removing any entries. Author is not responsible if anything goes wrong.
 */

var classesRootKey = Registry.ClassesRoot.OpenSubKey("Software\\Classes\\CLSID", true);
RegistryHelper.DeleteSubKeyTree(classesRootKey, "{B76C2E41-EB5A-43A0-850E-F610CDE565BA}");

var localMachineRootKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Demo App", true);
RegistryHelper.DeleteSubKeyTree(localMachineRootKey, "{B76C2E41-EB5A-43A0-850E-F610CDE565BA}");

var currentUserRootKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Demo App", true);
RegistryHelper.DeleteSubKeyTree(currentUserRootKey, "{B76C2E41-EB5A-43A0-850E-F610CDE565BA}");

 

The static class Registry, present under the Microsoft.Win32 namespace provides you static readonly value of type RegistryKey that returns you the registry root. This can be the HKEY_LOCAL_MACHINE (LocalMachine), HKEY_CLASSES_ROOT (ClassesRoot), HKEY_CURRENT_USER (CurrentUser) or any other value exposed by the class.

 

Here you can see the API implementation, for your reference:

namespace Microsoft.Win32
{
    public static class Registry
    {
        public static readonly RegistryKey ClassesRoot;
        public static readonly RegistryKey CurrentConfig;
        public static readonly RegistryKey CurrentUser;
        public static readonly RegistryKey LocalMachine;
        public static readonly RegistryKey PerformanceData;
        public static readonly RegistryKey Users;
    }
}

 

Now when you call the method to perform a delete operation, it will delete the entire key tree irrespective of any child element and/or value. Please take precaution and make sure that you have done all the validations before giving the actual call. As it is the heart of the system, performing anything unknowingly might cause your system not to boot. If you are unsure of what you are going to do, it’s better to make a backup of the registry or create a system restore point so that, you can revert back to a state if something goes wrong.

 

The above demonstration of the code is educational purpose only and the site/author is not responsible if something goes wrong due to negligence by the developer.

 


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter , Facebook , Google+ and LinkedIn . I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

0 comments


 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top