Get connection string from App.config

Moham ad Jafari picture Moham ad Jafari · Jun 30, 2011 · Viewed 693.6k times · Source
var connection = ConnectionFactory.GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);

And this is my App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

But when my project runs this is my error:

Object reference not set to an instance of an object.

Answer

Duffp picture Duffp · Jun 30, 2011

Can't you just do the following:

var connection = 
    System.Configuration.ConfigurationManager.
    ConnectionStrings["Test"].ConnectionString;

Your assembly also needs a reference to System.Configuration.dll