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.

How to get connection strings to various databases in ASP.NET 2.0

How to use connection strings to various Databases in ASP.NET 2.0

Some of the values and strings are used across all the pages of a website. It is a tedious process to code those values and strings in each page of the website.

The connection string will be used in many pages of the web site if you are developing a database driven website. Let us say that you have hard coded the connection string in all the pages, around 30 pages. Now if the value of the connection string changes, you have a headache of changing all the values of the connection string in all the 30 pages. This can’t be done easily and if you are to change the string again after about one month, it is going to be a tedious task.

Hence in such scenarios it is a practice to store those values in a central repository from where you can retrieve it and use it in all the pages. For example if you store the connection string in a central place like a web.config file you can retrieve those connection strings from the web.config file and use it. Previous to ASP.Net 2.0 the connection strings were stored in web.config file as given below:

<add key=”connectionString” value=”connection_string_value_here” />



The connection string is stored as key and value pair in the <appSettings> element of the web.config file. This value can be retrieved by writing code like:


Instead of using the <appSettings> section you can also add your own sections in the web.config file to have all your string value that you will be using in your application.

ASP.Net 2.0 provides with a special class for retrieving those customized string values.

This class is called the ConfigurationManager class.

Using this class you will be retrieving values by writing the following code for the above config file.


To open the ConnectionStrings section of the web.config file, you can use code like


The above code is used to retrieve ConnectionStrings from the web.config file as given below:

<add name=”connectionString” connectionString=”Data Source=.;Initial Catalog=db_products;Integrated Security=True” providerName=”System.Data.SqlClient” />

This code comes under the <configuration> section of the web.config file.

Here you can use the connectionStrings tag to store multiple Connection string to multiple databases and use it at your might.


<add name=”connectionString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

<add name=”myCString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

<add name=”newCString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

You can use it in you code like :

1. ConfigurationManager.ConnectionStrings[“connectionString”].ConnectionString

2. ConfigurationManager.ConnectionStrings[“myCString”].ConnectionString

3. ConfigurationManager.ConnectionStrings[“newCString”].ConnectionString

Happy Connecting to database 🙂