ebattulga
ebattulga

Reputation: 10981

How to delete a registry value in C#

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

Answers (6)

e1337
e1337

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

Shivaraj R
Shivaraj R

Reputation: 49

 string explorerKeyPath = @"Software\TestKey";
 using (RegistryKey explorerKey = Registry.CurrentUser.OpenSubKey(explorerKeyPath, writable: true))
 {
     if (explorerKey != null)
     {
         explorerKey.DeleteSubKeyTree("TestSubKey");
     }
 }

Upvotes: 1

Binoj Antony
Binoj Antony

Reputation: 16196

RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";

registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();

Upvotes: 15

Even Mien
Even Mien

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

Jon Skeet
Jon Skeet

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

Sören Kuklau
Sören Kuklau

Reputation: 19930

RegistryKey.DeleteValue

Upvotes: 1

Related Questions