Do you know how to use Connection String in .NET 2.0?
  v3.0 Posted at 20/10/2010 7:56 PM by System Account
In .NET 1.1 we used to store our connection string in a configuration file like this:


<add key="ConnectionString" value ="integrated security=true;
data source=(local);initial catalog=Northwind"/>

and access this connection string in code like this:

SqlConnection sqlConn = 
new SqlConnection(System.Configuration.ConfigurationSettings.
Bad example - old ASP.NET 1.1 way, untyped and prone to error.

In .NET 2.0 you can access it in another way

Step 1: Setup your settings in your common project. E.g. Northwind.Common

Settings in Project Properties
Figure: Settings in Project Properties

Step 2: Open up the generated App.config under your common project. E.g. Northwind.Common/App.config

Auto generated app.config
Figure: Auto generated app.config

Step 3: Copy the content into your entry applications app.config. E.g. Northwind.WindowsUI/App.config The new setting has been updated to app.config automatically in .NET 2.0

<add name="Common.Properties.Settings.NorthwindConnectionString"
connectionString="Data Source=(local);Initial Catalog=Northwind;
Integrated Security=True"
providerName="System.Data.SqlClient" />

Then you can access the connection string like this in C#

SqlConnection sqlConn =
new SqlConnection(Common.Properties.Settings.Default.NorthwindConnectionString);
Good example - access our connection string by strongly typed generated settings class.

Please note these steps does not work for web site model in Visual Studio 2005. However, they work for other projects such as Windows Form, Console application, Class Library and Web Application Project.

This is not an issue in a well designed website, since it's connection string will be defined in the data layer and you can overwrite this connection string in your web.config.

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address: