2009-02-10 11 views
27

È possibile ottenere/impostare valori di registro utilizzando la classe Microsoft.Win32.Registry. Ad esempio,Come eliminare un valore di registro in C#

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

Ma non riesco a cancellare alcun valore. Come cancellare un valore di registro?

risposta

70

Per eliminare il valore impostato nella tua domanda:

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

Guardate la documentazione per Registry.CurrentUser, RegistryKey.OpenSubKey e RegistryKey.DeleteValue per maggiori informazioni.

+1

Come posso cancellare l'intera cartella? supponiamo di voler eliminare '@" Software \ TeamViewer ";' –

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

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

codice non funzionante –

+0

Correggere l'errore, dovrebbe funzionare ora. –

11

Per eliminare tutte le sottochiavi/valori nella struttura (~ ricorsivamente), ecco un metodo di estensione che uso:

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

Sembra simile a qualcuno che lavora su .NET pensava che fosse una buona idea :) È stato aggiunto per .NET 4.0 http://msdn.microsoft.com/en-us/library/dd411622.aspx –

Problemi correlati