How to delete a registry value in C#

2019-01-04 13:08发布

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?

标签: c# registry
4条回答
霸刀☆藐视天下
3楼-- · 2019-01-04 13:50

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-04 13:50
RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";

registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();
查看更多
看我几分像从前
5楼-- · 2019-01-04 13:52

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);   
}
查看更多
登录 后发表回答