2010-12-23 5 views

Respuesta

23
var specificValue = ConfigurationManager.AppSettings["specificKey"]; 
if (!string.IsNullOrEmpty(specificValue)) 
{ 
    // Use the value 
} 

pero si sólo quiere comprobar la presencia también podría:

if (ConfigurationManager.AppSettings.AllKeys.Contains("specificKey")) 
{ 
    // the config file contains the specific key  
} 
+2

La segunda opción es malo - (ConfigurationManager.AppSettings.AllKeys.Contains ("specificKey")) no existe tal método – briler

+3

@briler: sí, existe. Mire el código de ejemplo aquí: http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.80%29.aspx Devuelve una matriz de cadenas y luego puede usar ' Contiene' en la matriz de cadenas. –

+0

No estoy seguro de si su primer ejemplo es correcto. Si no tiene esa clave en el archivo de configuración como specificKey como índice, obtendrá una excepción, ¿no? –

4

Prueba esto:

if(ConfigurationManager.AppSettings["yourkey"] != null) 
{ 
    // that key exists..... do something with it 
} 
Cuestiones relacionadas