Get connection string from App.config
757,844
Solution 1
You can just do the following:
var connection =
System.Configuration.ConfigurationManager.
ConnectionStrings["Test"].ConnectionString;
Your assembly also needs a reference to System.Configuration.dll
Solution 2
Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.
Solution 3
string str = Properties.Settings.Default.myConnectionString;
Solution 4
Also check that you've included the System.Configuration
dll under your references. Without it, you won't have access to the ConfigurationManager
class in the System.Configuration namespace.
Solution 5
First Add a reference of System.Configuration
to your page.
using System.Configuration;
Then According to your app.config get the connection string as follow.
string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();
That's it now you have your connection string in your hand and you can use it.
Author by
Admin
Updated on February 15, 2022Comments
-
Admin about 2 years
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.
-
David Colwell almost 11 yearsLove this answer. By default in my version of VS (VS2012 Ultimate) this library is not included, but
using System.Configuration
still works -
FrenkyB about 9 yearsWhat if app.config is added as a link to a project ?
-
Amit Sinha over 7 yearsI did the same as u said but same null reference error I am getting.
-
Jacqlyn about 7 yearsI know that this is a C# question, but since this is the top of the google search results, to do this in VB, it's
System.Configuration.ConfigurationManager.ConnectionStrings("Test").ConnectionString
for those of us who have to maintain VB code -
CodingYourLife over 6 yearsI really HAD TO add the reference or the using was not underlined but still ConfigurationManager unknown. Thanks!
-
BrainSlugs83 almost 6 yearsThis will only work if your connection string is an app setting, it will not work if to retrieve
<connectionStrings>
elements from app.config (which is what the OP is asking for!).