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.
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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.
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.
You can just do the following:
var connection = System.Configuration.ConfigurationManager. ConnectionStrings["Test"].ConnectionString;
Your assembly also needs a reference to System.Configuration.dll
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With