Problem Statement

There might be a  chance of missing the appSettings Key and it leads to an runtime exception when system doesn’t found particular Key.

Solution

For this we have couple of solutions, but in each the ultimate goal is to verify whether the given key exist in appSettings list before trying to read its value. So, following is the two ways to identify whether the given Key exist in appsSettings or not.

Approach-1:

This can be done using a collection’s Contains method as shown below

if (ConfigurationManager.AppSettings.AllKeys.Contains("EnableLog")) 
{
if (ConfigurationManager.AppSettings["EnableLog"].ToUpper() == "YES") 
{ 

 //your code here 

} 
}

Approach-2:

This can be done using a LINQ as shown below

if (ConfigurationManager.AppSettings.AllKeys.Any(s=>s=="EnableLog")) 
{
if (ConfigurationManager.AppSettings["EnableLog"].ToUpper() == "YES") 
{ 

 //your code here 

} 
}

Mostly, people will believe that the following code will solve the issue but beware the following line also generates runtime exception why because CLR executes ConfigurationManager.AppSettings[“myKey”] statement first and then identifies that Key doesn’t exist and raises exception.

String.TryParse(ConfigurationManager.AppSettings["EnableLog"], out myvariable);

Hope this information helped you.

Happy Coding 🙂