如何在 C# 中删除注册表值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/531151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:00:55  来源:igfitidea点击:

How to delete a registry value in C#

c#registry

提问by ebattulga

I can get/set registry values using the Microsoft.Win32.Registry class. For example,

我可以使用 Microsoft.Win32.Registry 类获取/设置注册表值。例如,

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?

但我无法删除任何值。如何删除注册表值?

采纳答案by Jon Skeet

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.OpenSubKeyand RegistryKey.DeleteValuefor more info.

看看文档进行Registry.CurrentUserRegistryKey.OpenSubKeyRegistryKey.DeleteValue获取更多信息。

回答by Binoj Antony

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

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

回答by Even Mien

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);   
}