如何确定appconfig包含特定键

10
2个回答

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

但如果你只想检查是否存在,你也可以这样做:

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

2
你的第二个选项是错误的 - (ConfigurationManager.AppSettings.AllKeys.Contains("specificKey")) 没有这样的方法。 - briler
3
有的。看这里的示例代码:http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.80%29.aspx. 它返回一个字符串数组,你可以在该字符串数组上使用 Contains 方法。 - user195488
我不确定你的第一个例子是否正确。如果在配置文件中没有像specificKey这样的键作为索引,那么你会得到异常,不是吗? - Artem A

4

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接