How to handle ConfigurationErrorsException?

ipjyo
ipjyo used Ask the Experts™
on
I have the below lines to read values from appsettings in app.config file. I want to handle the exceptions that might be thrown when the key is missing in app.config file. What is the best way to handle this? Thanks for any help.

processor.UserId = ConfigurationManager.AppSettings["userid"];
processor.Password = ConfigurationManager.AppSettings["password"];

<appSettings>
            <add key="userid" value ="UN"/>
            <add key="password" value ="PWD"/>
</appSettings>

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Research & Development Manager
Commented:
Test that the keys exist prior to assigning them to your variables:
using System;
using System.Configuration;

namespace EE.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string userID, password, nonExistantKey;
                if (ConfigurationManager.AppSettings["userid"] != null)
                {
                    userID = ConfigurationManager.AppSettings["userid"].ToString();
                }
                if (ConfigurationManager.AppSettings["password"] != null)
                {
                    password = ConfigurationManager.AppSettings["password"].ToString();
                }
                if (ConfigurationManager.AppSettings["nonExistantKey"] != null)
                {
                    nonExistantKey = ConfigurationManager.AppSettings["nonExistantKey"].ToString();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
            Console.ReadLine();
        }
    }
}

// App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="userid" value ="UN"/>
    <add key="password" value ="PWD"/>
  </appSettings>
</configuration>

Open in new window

Author

Commented:
Thank you.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial