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

eba*_*lga 40 c# registry

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

Microsoft.Win32.Registry.SetValue(
    @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
    "MyApp", 
    Application.ExecutablePath);
Run Code Online (Sandbox Code Playgroud)

但我不能删除任何值.如何删除注册表值?

Jon*_*eet 91

要删除问题中设置的值:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

看看文档进行Registry.CurrentUser,RegistryKey.OpenSubKeyRegistryKey.DeleteValue获取更多信息.


Eve*_*ien 16

要删除树中的所有子键/值(〜递归),这是我使用的扩展方法:

public static void DeleteSubKeyTree(this RegistryKey key, string subkey, 
    bool throwOnMissingSubKey)
{
    if (!throwOnMissingSubKey && key.OpenSubKey(subkey) == null) { return; }
    key.DeleteSubKeyTree(subkey);
}
Run Code Online (Sandbox Code Playgroud)

用法:

string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
   key.DeleteSubKeyTree("MyApp",false);   
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来像是一个在.NET上工作的人认为这也是个好主意:)为.NET 4.0添加了http://msdn.microsoft.com/en-us/library/dd411622.aspx (7认同)

Bin*_*ony 12

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

registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();
Run Code Online (Sandbox Code Playgroud)