2009-02-10 86 views
27

我可以使用Microsoft.Win32.Registry類獲取/設置註冊表值。例如,如何刪除C#中的註冊表值

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

但我無法刪除任何值。我如何刪除註冊表值?

回答

70

要刪除你的問題設置的值:

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獲取更多信息。

+1

如何刪除整個文件夾?假設我想刪除`@「Software \ TeamViewer」;` – 2012-01-03 13:34:28

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

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

非工作代碼 – 2010-03-16 13:13:50

11

要刪除樹(〜遞歸)的所有子項/值,下面是我使用的擴展方法:

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