2009-02-10 33 views
27

Puedo obtener/establecer valores de registro utilizando la clase Microsoft.Win32.Registry. Por ejemplo,Cómo eliminar un valor de registro en C#

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

Pero no puedo eliminar ningún valor. ¿Cómo elimino un valor de registro?

Respuesta

70

Para eliminar el valor establecido en su pregunta:

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

mirada a los documentos de Registry.CurrentUser, RegistryKey.OpenSubKey y RegistryKey.DeleteValue para obtener más información.

+1

¿Cómo puedo eliminar toda la carpeta? Supongamos que quiero eliminar '@" Software \ TeamViewer ";' –

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

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

código que no funciona –

+0

Corregido el error, debería funcionar ahora. –

11

Para eliminar todas las subclaves/valores en el árbol (~ recursiva), que aquí es un método de extensión que utilizo:

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

Uso:

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

Parece que alguien trabajando en .NET pensó que esto también era una buena idea :) Se agregó para .NET 4.0 http://msdn.microsoft.com/en-us/library/dd411622.aspx –

Cuestiones relacionadas