如何删除C#中的registry值

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

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

但是我不能删除任何值。 如何删除registry值?

要删除问题中设置的值:

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

查看Registry.CurrentUserRegistryKey.OpenSubKeyRegistryKey.DeleteValue的文档以获取更多信息。

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

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

用法:

 string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) { key.DeleteSubKeyTree("MyApp",false); } 
 RegistryKey registrykeyHKLM = Registry.LocalMachine; string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp"; registrykeyHKLM.DeleteValue(keyPath); registrykeyHKLM.Close(); 

RegistryKey.DeleteValue