10

Possible Duplicate:
C# assembly > app settings > how to check if one exists?

In the app.config, How can I know if it contains a specific key?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

2 Answers2

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

but if you only want to check the presence you could also:

if (ConfigurationManager.AppSettings.AllKeys.Contains("specificKey"))
{
    // the config file contains the specific key    
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    your second option is wrong - (ConfigurationManager.AppSettings.AllKeys.Contains("specificKey")) there isn'y such method – briler Mar 20 '13 at 10:29
  • 3
    @briler: Yes there is. Look at the example code here: http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.80%29.aspx It returns a string array and then you can use `Contains` on the string array. –  Apr 22 '13 at 19:27
  • I'm not sure about your first example is correct. If you have no such key in config file like specificKey as index, you will get exception, don't you? – Artem A Mar 27 '17 at 15:44
4

Try this:

if(ConfigurationManager.AppSettings["yourkey"] != null)
{
   // that key exists..... do something with it
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459