How to use appSettings and connectionStrings in C#

For the developers in C# the most useful file is the App.Config or the Web.Config file and the most used settings in appSettings. You can use any name for the configuration file. Even you can use Multiple configuration file in you application.

This configuration file is an XML file having  .config extension. The .NET Framework provides the System.Configuration.ConfigurationManager.AppSettings namspace which lets you to retrieve appSettings elements from the configuration file. Data is stored in key/value pairs as shown in this sample .config file:

<add key="ServiceName" value="Test  Service"/>
<add key="ServiceDisplayName" value="Test Display Service"/>
<add key="ServiceDescription" value="Test Description"/>

Now, to read this appSettings you need to include System.Configuration (2.0) in to your application.

Here is a sample code that reads the required appSettings for your application:

String _serviceName = ConfigurationManager.AppSettings[“ServiceName”].Trim();
String _serviceDisplayName = ConfigurationManager.AppSettings[“ServiceDisplayName”].Trim();
String _serviceDesc = ConfigurationManager.AppSettings[“ServiceDescription”].Trim();

Now, you can use all these 3 variables as you like in your application. You can also use a NULL value check before assignment like this:

String _serviceDesc = (null != ConfigurationManager.AppSettings[“ServiceDescription”].Trim())
? ConfigurationManager.AppSettings[“ServiceDescription”].Trim() : “Default Value”;

The following example code reads all the appSettings from the config file in your application:

    // Get the AppSettings section.        
    // This function uses the AppSettings property
    // to read the appSettings configuration 
    // section.
    public static void ReadAppSettings()
        // Get the AppSettings section.
        NameValueCollection appSettings =

        // Get the AppSettings section elements.
        Console.WriteLine("Using AppSettings property.");
        Console.WriteLine("Application settings:");

        if (appSettings.Count == 0)
          Console.WriteLine("[ReadAppSettings: {0}]",
          "AppSettings is empty Use GetSection command first.");
        for (int i = 0; i < appSettings.Count; i++)
          Console.WriteLine("#{0} Key: {1} Value: {2}",
            i, appSettings.GetKey(i), appSettings[i]);
      catch (ConfigurationErrorsException e)
        Console.WriteLine("[ReadAppSettings: {0}]",

In some cases you might want to save user input to your appSettings. So, you need to create new appSettings Dynamically or Change an existing one. The following code section demonstrates how to create a new appSettings section. I believe the modification part can be done by looking at these 2 examples:

    // Create the AppSettings section.
    // The function uses the GetSection(string)method 
    // to access the configuration section. 
    // It also adds a new element to the section collection.

    public static void CreateAppSettings()
      // Get the application configuration file.
      System.Configuration.Configuration config =

      string sectionName = "appSettings";

      // Add an entry to appSettings.
      int appStgCnt =
      string newKey = "NewKey" + appStgCnt.ToString();

      string newValue = DateTime.Now.ToLongDateString() +
        " " + DateTime.Now.ToLongTimeString();

      config.AppSettings.Settings.Add(newKey, newValue);

      // Save the configuration file.

      // Force a reload of the changed section. This
      // makes the new values available for reading.

      // Get the AppSettings section.
      AppSettingsSection appSettingSection =

      Console.WriteLine("Using GetSection(string).");
      Console.WriteLine("AppSettings section:");


To Read a connectionString from app.config / web.config you can use the following code:

public string GetConnectionString(string str)
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString;
return conn;
//In all other cases return null
return null;

This method will return the named connection string. The Key Name needs to be pass to the method as input , else it will return null.

Assuming you have the following in your config file:

<add name=”MyConnString1″ connectionString=”<connection string 1>” providerName=”<provider1>” />
<add name=”MyConnString2″ connectionString=”<connection string 2>” providerName=”<provider2>” />

Here, we have 2 separate connectionStrings. You can have as many as you want. To use it, you just need to call the above method with the name like this:

String _connecitonString = GetConnectionString("MyConnectionString1");

if(null != _connecitonString){
//Your code

Now if you want to read all Connection Strings then you need to use the following code:

    // Get the ConnectionStrings section.        
    // This function uses the ConnectionStrings 
    // property to read the connectionStrings
    // configuration section.
    public static void ReadConnectionStrings()

      // Get the ConnectionStrings collection.
      ConnectionStringSettingsCollection connections =

      if (connections.Count != 0)
        Console.WriteLine("Using ConnectionStrings property.");
        Console.WriteLine("Connection strings:");

        // Get the collection elements.
        foreach (ConnectionStringSettings connection in
          string name = connection.Name;
          string provider = connection.ProviderName;
          string connectionString = connection.ConnectionString;

          Console.WriteLine("Name:               {0}",
          Console.WriteLine("Connection string:  {0}",
         Console.WriteLine("Provider:            {0}",
        Console.WriteLine("No connection string is defined.");

You can read more about appSettings and connectionStrings in MSDN.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s