2010-11-25 27 views
56

¿Cómo comprobar si existe un valor de registro mediante el código C#? Este es mi código, quiero verificar si existe 'Inicio'.¿Cómo verificar si existe un valor de registro usando C#?

public static bool checkMachineType() 
{ 
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true); 
    string currentKey= winLogonKey.GetValue("Start").ToString(); 

    if (currentKey == "0") 
     return (false); 
    return (true); 
} 

Respuesta

44

Para la clave del registro puede comprobar si es nula después de recibirla. Será, si no existe.

Para el valor del registro puede obtener los nombres de los valores para la clave actual y comprobar si esta matriz contiene el nombre del valor necesario.

+15

ejemplo de esto último, ya que es lo que pide la pregunta? – cja

+2

No puedo creer que esta sea la respuesta aceptada o.O – lewis4u

20
string [email protected]"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia"; 
string valueName="Start"; 
if (Registry.GetValue(keyName, valueName, null) == null) 
{ 
    //code if key Not Exist 
} 
else 
{ 
    //code if key Exist 
} 
+11

¿Qué pasa si el valor de la clave es '" no existe "'? Lo que significa que 'defaultValue' no es para verificación de existencia de clave, es para evitar verificación nula adicional. – abatishchev

+0

@ben cambió el valor predeterminado de '" not exist "' to 'null' (por lo tanto, se corrigió el código). Entonces, el comentario anterior de @abatishchev ya no se aplica. –

35
public static bool registryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName) 
{ 
    RegistryKey root; 
    switch (hive_HKLM_or_HKCU.ToUpper()) 
    { 
     case "HKLM": 
      root = Registry.LocalMachine.OpenSubKey(registryRoot, false); 
      break; 
     case "HKCU": 
      root = Registry.CurrentUser.OpenSubKey(registryRoot, false); 
      break; 
     default: 
      throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\""); 
    } 

    return root.GetValue(valueName) != null; 
} 
+0

Si bien esta respuesta es definitivamente correcta, esta pregunta ya fue respondida. – hsanders

+25

@hsanders, incluso si la pregunta ya fue respondida, siempre es bienvenido agregar información útil. El desbordamiento de pila recibe mucho tráfico de Google;) – DonkeyMaster

+2

root.GetValue (valueName)! = Null arroja la excepción si valueName no existe. – Farukh

3
RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false); 
     if (rkSubKey == null) 
     { 
      // It doesn't exist 
     } 
     else 
     { 
      // It exists and do something if you want to 
     } 
+1

esta solución es verificar si la clave existe o no. para el valor tenemos que verificar la lista de valores en esa clave – jammy

-1
 internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value) 
     { 
      // get registry key with Microsoft.Win32.Registrys 
      RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object. 
      if ((rk) == null) // if the RegistryKey is null which means it does not exist 
      { 
       // the key does not exist 
       return false; // return false because it does not exist 
      } 
      // the registry key does exist 
      return true; // return true because it does exist 
     }; 

uso:

 // usage: 
     /* Create Key - while (loading) 
     { 
      RegistryKey k; 
      k = Registry.CurrentUser.CreateSubKey("stuff"); 
      k.SetValue("value", "value"); 
      Thread.Sleep(int.MaxValue); 
     }; // no need to k.close because exiting control */ 


     if (regKey(@"HKEY_CURRENT_USER\stuff ... ", "value")) 
     { 
      // key exists 
      return; 
     } 
     // key does not exist 
0
 RegistryKey test9999 = Registry.CurrentUser; 

     foreach (var item in test9999.GetSubKeyNames()) 
     { 
      if (item.ToString() == "SOFTWARE") 
      { 
       test9999.OpenSubKey(item); 

       foreach (var val in test9999.OpenSubKey(item).GetSubKeyNames()) 
       { 
        if(val.ToString() == "Adobe") { 
         Console.WriteLine(val+ " found it "); 
        } 
       } 
      } 
     } 
Cuestiones relacionadas