Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get connection string from App.config

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.

like image 358
Moham ad Jafari Avatar asked Jun 30 '11 14:06

Moham ad Jafari


People also ask

How do you read Connectionstring from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

What is connection string in app?

Applications use connection strings to identify the server instance and database to connect to and to determine what driver, login, etc. to use to connect to the SQL Server instance. Typically, the connection string will be stored in a configuration file somewhere within the application or web server.

How do I find the connection string in SQL Server?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.


1 Answers

You can just do the following:

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

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

like image 71
Duffp Avatar answered Oct 02 '22 17:10

Duffp