如何检查appSettings键是否存在?

如何检查appSettings键是否存在?

问题描述:

如何检查应用程序设置是否可用?如何检查appSettings键是否存在?

即app.config中

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

并在的CodeFile

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 
} 
+2

我们有一个[类似SQL的IsNull函数(https://gist.github.com/eithe/5589891)在我们的图书馆,这使得检索设置非常方便:'Dim configValue As String = Util.IsNull(ConfigurationManager.AppSettings.Get(“SettingName”),String.Empty)' – 2013-05-16 07:00:05

+7

它引发“没有设置对象实例的对象引用” – 2013-06-03 08:14:48

+0

不,这是错误的。如果“myKey”在应用程序设置xml节点中不存在,则代码将引发异常。 – Gionata 2016-06-27 10:41:10

if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey")) 
{ 
    // Key exists 
} 
else 
{ 
    // Key doesn't exist 
} 
+0

如果你以后不想使用这个值,这可能会稍微更有效率(?)。这个问题特别提到测试'如果应用程序设置可用'。既然可用性意味着想要在我脑海中使用它,我会说user195488提供的答案对于来到这里的人会更有用 - 但严格来说,你的答案也是正确的。 – 2014-09-11 19:09:17

+5

这对于一个简单的事实来说是一个更好的解决方案,它实际上是检查密钥是否存在。如果我对我的密钥有空白值,user195488提供的解决方案会给我一个误报。 – dyslexicanaboko 2014-09-30 19:40:53

+2

此解决方案不正确。 AppSettings是一个NameValueCollection,当涉及到键查找时,它默认为**不区分大小写**。然而,您在此处使用的LINQ .Contains扩展方法将默认为**区分大小写的**比较。 – Jax 2015-06-04 19:00:06

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

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

或者,如代码猴建议:

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

上的选项给了灵活,所有的方式,如果你知道密钥类型尝试解析它们 bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);

我认为LINQ表达可能是最佳:

const string MyKey = "myKey" 

    if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey)) 
      { 
       // Key exists 
      } 
+0

当然...但idunno - 这种方法有什么_advantage_?如果我真的很熟悉Linq(大多数C#程序员可能最终会这样做),那么阅读这个例子可能会很容易,但我认为它不会是_easier_--所以除非有效率优势...为什么? – 2014-09-11 19:12:28

+0

没有效率优势和语法冗长的imo。 – 2015-10-06 14:51:25

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

通过泛型和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);