Monday, December 11, 2006 1:08 PM bart

Windows Vista - Registry programming tip: RegDeleteTree

Assume you have some registry key you want to delete in its entirety, meaning you want to delete it with all children and subtrees. A sample is depicted below (HKCU\MyDemo):

Chances are high you've tried to delete the key with the following piece of code (well, at least in some language or another using the RegDeleteKey function of advapi32):

using System;
using System.Runtime.InteropServices;

namespace RegDeleteTreeDemo
{
   class Program
   {
      [DllImport("advapi32.dll")]
      static extern int RegDeleteKey(uint hKey, string lpSubkey);

      static uint HKEY_CURRENT_USER = 0x80000001;

      static void Main(string[] args)
      {
         int res = RegDeleteKey(HKEY_CURRENT_USER, "MyDemo");
      }
   }
}

If you've tried this at home you'll know it isn't that easy. Effectively, it's like doing an rd on a non-empty directory. The Windows SDK mentions: "The subkey to be deleted must not have subkeys. To delete a key and all its subkeys, you need to enumerate the subkeys and delete them individually." and a sample is available that illustrates doing this.

There are however better alternatives if you really want to delete a whole key with all its descendants. There's a function called SHDeleteKey defined in SHLWAPI but in Windows Vista this functionality has been added to advapi32 as well using RegDeleteTree. A sample is shown below:

using System;
using System.Runtime.InteropServices;

namespace RegDeleteTreeDemo
{
   class Program
   {
      [DllImport("advapi32.dll")]
      static extern int RegDeleteTree(uint hKey, string lpSubkey);

      static uint HKEY_CURRENT_USER = 0x80000001;

      static void Main(string[] args)
      {
         int res = RegDeleteTree(HKEY_CURRENT_USER, "MyDemo");
      }
   }
}

It's as easy as this, and now the deletion works like a charm. So, time to get rid of recursive tree deletion stuff.

Warning: Extra care is recommended when working with this function; I'm not responsible for accidental deletions of things like HKCU\Software (haven't tried it myself, don't know whether it would work, expect it would, but don't want to know it at all).

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under: ,

Comments

# Windows Vista - Registry programming tip: RegDeleteTree

Saturday, December 16, 2006 4:56 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com