Reputation: 10981
I can get/set registry values using the Microsoft.Win32.Registry class. For example,
Microsoft.Win32.Registry.SetValue(
@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
"MyApp",
Application.ExecutablePath);
But I can't delete any value. How do I delete a registry value?
Upvotes: 53
Views: 94387
Reputation: 1
I Needed something a little different, I just needed to delete everything a key contained. Therefore the below
Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\YourNeededKeyThatHasMany\");
Note that here its using LocalMachine so it's looking in "HKEY_LOCAL_MACHINE" for the Key to delete its SubTreeKeys. Was simpler for me to do this and would've liked to see this simple answer here.
Upvotes: 0
Reputation: 49
string explorerKeyPath = @"Software\TestKey";
using (RegistryKey explorerKey = Registry.CurrentUser.OpenSubKey(explorerKeyPath, writable: true))
{
if (explorerKey != null)
{
explorerKey.DeleteSubKeyTree("TestSubKey");
}
}
Upvotes: 1
Reputation: 16196
RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";
registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();
Upvotes: 15
Reputation: 45898
To delete all subkeys/values in the tree (~recursively), here's an extension method that I use:
public static void DeleteSubKeyTree(this RegistryKey key, string subkey,
bool throwOnMissingSubKey)
{
if (!throwOnMissingSubKey && key.OpenSubKey(subkey) == null) { return; }
key.DeleteSubKeyTree(subkey);
}
Usage:
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
key.DeleteSubKeyTree("MyApp",false);
}
Upvotes: 18
Reputation: 1500515
To delete the value set in your question:
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
if (key == null)
{
// Key doesn't exist. Do whatever you want to handle
// this case
}
else
{
key.DeleteValue("MyApp");
}
}
Look at the docs for Registry.CurrentUser
, RegistryKey.OpenSubKey
and RegistryKey.DeleteValue
for more info.
Upvotes: 110