如何检查一个appSettings键是否存在?

如何检查应用程序设置是否可用?

即app.config

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key ="someKey" value="someValue"/> </appSettings> </configuration> 

并在代码文件中

 if (ConfigurationManager.AppSettings.ContainsKey("someKey")) { // Do Something }else{ // Do Something Else } 

MSDN:Configuration Manager.AppSettings

 if (ConfigurationManager.AppSettings[name] != null) { // Now do your magic.. } 

要么

 string s = ConfigurationManager.AppSettings["myKey"]; if (!String.IsNullOrEmpty(s)) { // Key exists } else { // Key doesn't exist } 
 if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey")) { // Key exists } else { // Key doesn't exist } 

我认为LINQexpression可能是最好的:

  const string MyKey = "myKey" if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey)) { // Key exists } 

如果您正在查找的密钥不存在于configuration文件中,那么您将无法使用.ToString()将其转换为string,因为该值将为空,您将得到“未设置对象引用到一个对象的实例“错误。 在尝试获取string表示之前,最好先查看该值是否存在。

 if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["myKey"])) { String myKey = ConfigurationManager.AppSettings["myKey"].ToString(); } 

或者,正如Code Monkey所言:

 if (ConfigurationSettings.AppSettings["myKey"] != null) { // Now do your magic.. } 

var isAlaCarte = ConfigurationManager.AppSettings.AllKeys.Contains(“IsALaCarte”)&& bool.Parse(ConfigurationManager.AppSettings.Get(“IsALaCarte”));

通过generics和LINQ安全地返回默认值。

 public T ReadAppSetting<T>(string searchKey, T defaultValue) { if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == searchKey)) { try { // see if it can be converted var converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null) { defaultValue = (T)converter.ConvertFromString(ConfigurationManager.AppSettings.GetValues(searchKey).First()); } } catch { } // nothing to do, just return default } return defaultValue; } 

用法如下:

 string LogFileName = ReadAppSetting("LogFile","LogFile"); double DefaultWidth = ReadAppSetting("Width",1280.0); double DefaultHeight = ReadAppSetting("Height",1024.0); Color DefaultColor = ReadAppSetting("Color",Colors.Black); 

如果你知道键types尝试parsing他们bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);