C# – Get connection string from App.config

ado.netapp-configc++connection-stringexception-handling

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.

Best Solution

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

Related Question