C#.NET: How to store and get connection strings from config files

Last updated on 22nd September 2022

A connection string a list of key-value pairs separated by semicolon which contains the information necessary to establish a connection to a data source. It is highly recommended that you store connection strings in application config files (app.config or web.config) so that you can change them anytime without needing to recompile the application. You can also have multiple connection strings, for example one for your development environment, one for staging and one for production. Each of these connection strings could be pointing to a different data source. This post demonstrates how to store and retrieve connection strings from app.config file of a C# .Net Windows application. The procedure is same for ASP.NET applications also except that the connection strings are stored in web.config file instead of app.config.

Storing Connection String in Config File

The recommended method for storing connection strings is in the application configuration file(app.config), under connectionStrings section of the configuration element. Here is an example of a connection string for a Oracle Database connection in the configuration section of app.config.

<?xml version="1.0" encoding="utf-8"?> 

<configuration>  

  <connectionStrings>  
    <add name="MyConnection" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyDBHost)(PORT=1521))(SERVICE_NAME=MyOracleSID))); User Id=myUserName; Password=myPassword;" />
  </connectionStrings>  

</configuration>

The <connectionStrings> section has a child element <add> which has two attributes – Name and ConnectionString.

  • Name attribute defines a name that uniquely identifies a connection. It is case insensitive and can be used to retrieve the connection string during runtime.

  • connectionString attribute contains a set of key-value pairs that specifies various connection parameters. These can be different depending on the type of database, connection type, authentication etc.,

  • A connection string may also contain a ProviderName attribute. ProviderName is a fully qualified name for the .NET data provider used for this connection. For example,

    • ProviderName=”System.Data.SqlClient” for Microsoft SQL Server data access
    • ProviderName=”System.Data.OracleClient” for Oracle data access

Get Connection String from app.config

You can get connection strings programaticlly during runtime using the ConfigurationManager class defined in System.Configuration namespace.

  1. Add a reference to System.Configuration in your project.

    • Right-click your project in the Solution Explorer and select Add → Reference
    • Select System.Configuration and click OK.

      System Configuration
  2. Include System.Configuration namespace in the class where you want access the connection string.

    using System.Configuration;
    
  3. Get connection string using ConnectionStrings property of ConfigurationManager class.

    string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
    

    Where MyConnection is the name of the connection as specified in the config file.

Here is a full example of accessing connection string by name from app.config file in a Windows Forms Application.

using System;
using System.Windows.Forms;
namespace myApplication
{
 static class Program
 {
   /// <summary>
   /// The main entry point for the application.
   /// </summary>
   [STAThread]
   static void Main()
   {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString
     
     Application.Run(new Form1());
	
    }
 }
}

Get Connection String by Provider Name

Typcially you get ConnectionString by Name just as in the previous example. You could retrieve connection strings by ProviderName also. For example, consider you have a connection string like below in your config file.

  <connectionStrings>  
    <add name="MyConnection" ProviderName="System.Data.OracleClient" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyDBHost)(PORT=1521))(SERVICE_NAME=MyOracleSID))); User Id=myUserName; Password=myPassword;" />
  </connectionStrings>  

To get this Connection string by ProviderName, you can iterate through every connection string to find a match for your provider name.

string providerName = "System.Data.OracleClient ";
string cs;

foreach (ConnectionStringSettings conStr in ConfigurationManager.ConnectionStrings)
{
  if (conStr.ProviderName == providerName)
  {
    cs = conStr.ConnectionString;
    break;
  }
}

ConfigurationManager class also has a AppSettings property which can be used to get data from code>appsettings section of the config file.

Storing database access credentials as plain text in config file poses a security risk. There are a few ways to overcome this risk. If you are using SQL Server for example you could enable Windows Authentication in which case you do not have to expose username and password in the config file. Another solution is to encrypt the config file. Encrypting config files will be explained in detail on the next post.


Post a comment

Comments

bklooste | March 20, 2023 10:50 AM |

System.Configuration should be avoided .. use the newer stuff

Anthon | January 14, 2023 8:48 PM |

Thanks, this is a real help.