How do I check to see if an Application Setting is available?
i.e. app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="someKey" value="someValue"/>
</appSettings>
</configuration>
and in the codefile
if (ConfigurationManager.AppSettings.ContainsKey("someKey"))
{
// Do Something
}else{
// Do Something Else
}
MSDN: Configuration Manager.AppSettings
or
If the key you are looking for isn't present in the config file, you won't be able to convert it to a string with .ToString() because the value will be null and you'll get an "Object reference not set to an instance of an object" error. It's best to first see if the value exists before trying to get the string representation.
Or, as Code Monkey suggested:
Safely returned default value via generics and LINQ.
Used as follows:
I think the LINQ expression may be best:
var isAlaCarte = ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") && bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));