I am trying to delete registry key and its subkeys. My method takes a registry key as a string argument, and then locates and deletes it.
I am testing it with this key:
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\InstallShield_{694AFFC3-93D4-4049-AF26-78739488EB4D}
And this is the method I have written:
static void RemoveRegKey(string registryKey)
{
// Split the string to get the hive, middle section, and subkey name
string[] regKeyParts = registryKey.Split('\\');
// Hive
string hive = regKeyParts[0].ToUpper();
// Name
string name = regKeyParts[regKeyParts.Length - 1];
// Middle bit
string keyPath = "";
for (int i = 1; i < regKeyParts.Length - 1; i++)
{
keyPath = keyPath + regKeyParts[i] + "\\";
}
// Create my registry key
RegistryKey regkey = null;
switch (hive)
{
case ("HKEY_LOCAL_MACHINE"):
regkey = Registry.LocalMachine;
break;
case ("HKEY_CURRENT_CONFIG"):
regkey = Registry.CurrentConfig;
break;
case ("HKEY_CURRENT_USER"):
regkey = Registry.CurrentUser;
break;
case ("HKEY_USERS"):
regkey = Registry.Users;
break;
case ("HKEY_CLASSES_ROOT"):
regkey = Registry.ClassesRoot;
break;
}
// Open the registry key (everything up to the parent of the key I want to delete
using (RegistryKey rk = regkey.OpenSubKey(keyPath, true))
{
Console.WriteLine(rk.ToString());
// This bit added to verify the subkey is present - it will output to console if found
string[] sk = rk.GetSubKeyNames();
foreach (string s in sk)
{
if (s == name) { Console.WriteLine(s); }
}
// If the subkey is present, delete it
if (regkey.OpenSubKey(name) != null)
{
Console.WriteLine("Registry key found - deleting it");
regkey.DeleteSubKeyTree(name);
}
else
{
Console.WriteLine("Could not find reg key");
}
}
}
The key is definitely present, as this section:
string[] sk = rk.GetSubKeyNames();
foreach (string s in sk)
{
if (s == name) { Console.WriteLine(s); }
}
gives the expected output shown in green here:
However, regkey.OpenSubKey(name)
evaluates to null
, as the output after shows.
Could not find reg key.
I am running this as an elevated user, and the key is not protected.