Store My Connection String Please - ConfigurationManager in .NET 2.0

I love the neat little features. You know, the ones that aren't earth shattering but still get you excited over the simplicity involved. To me, the .NET 2.0 Framework's System.Configuration namespace's ConfigurationManager class qualifies as one of those things. Specifically, I like the ConfigurationManager's ConnectionString property. Here is a simple example ... I can create a connection string section in my class library project's App.config file and then access the connection string through code. Yeah, there are other ways to do it but this is just cool. Its simple. Its clean.

Here is a sample App.config:

<FONT color=#0000ff size=2>

<?<FONT color=#800000 size=2>xml<FONT color=#ff00ff size=2> <FONT color=#ff0000 size=2>version<FONT color=#0000ff size=2>="1.0"<FONT color=#ff00ff size=2> <FONT color=#ff0000 size=2>encoding<FONT color=#0000ff size=2>="utf-8"<FONT color=#ff00ff size=2> <FONT color=#0000ff size=2>?>

<<FONT color=#800000 size=2>configuration<FONT color=#0000ff size=2>>

<FONT size=2>

<FONT color=#0000ff size=2>   <<FONT color=#800000 size=2>connectionStrings<FONT color=#0000ff size=2>>

<FONT size=2>

<FONT color=#0000ff size=2>      <<FONT color=#800000 size=2>add<FONT color=#ff00ff size=2> <FONT color=#ff0000 size=2>name<FONT color=#0000ff size=2>="MyCnString"<FONT color=#ff00ff size=2>

<FONT color=#ff0000 size=2>      connectionString<FONT color=#0000ff size=2>="Data Source=legolas;Initial Catalog=Northwind;Integrated Security=True"<FONT color=#ff00ff size=2>

<FONT color=#ff0000 size=2>      providerName<FONT color=#0000ff size=2>="System.Data.SqlClient"/>

<FONT size=2>

<FONT color=#0000ff size=2>   </<FONT color=#800000 size=2>connectionStrings<FONT color=#0000ff size=2>>

</<FONT color=#800000 size=2>configuration<FONT color=#0000ff size=2>>

 

Add a reference to the System.Configuration.dll and then add a using statement like this :

<FONT color=#0000ff size=2>   using System.Configuration;<FONT color=#0000ff size=2> 

 

The code to grab the connection string could then look like this: 

<FONT color=#0000ff size=2>   string cnString = ConfigurationManager.ConnectionStrings["MyCnString"].ConnectionString;
   SqlConnection cn = new SqlConnection(cnString);


Again, nothing earth shattering but its nice to have a place to store your connection strings.

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders

Tags:
All