Read connection string from web.config
434,638
Solution 1
Add System.Configuration
as a reference.
For some bizarre reason it's not included by default.
Solution 2
You need to add a reference to System.Configuration
and then use:
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
Solution 3
C#
// Add a using directive at the top of your code file
using System.Configuration;
// Within the code body set your variable
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
VB
' Add an Imports statement at the top of your code file
Imports System.Configuration
' Within the code body set your variable
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString
Solution 4
Add System.Configuration
as a reference then:
using System.Configuration;
...
string conn =
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
Solution 5
I guess you need to add a reference to the System.Configuration assembly if that have not already been added.
Also, you may need to insert the following line at the top of your code file:
using System.Configuration;
Related videos on Youtube
Author by
chamara
ASP.NET, ASP.NET MVC , Sql Server, Bootstrap, CSS and Crystal reports developer
Updated on January 08, 2020Comments
-
chamara over 4 years
How can I read a connection string from a
web.config
file into a public class contained within a class library?I've tried:
WebConfigurationManager ConfigurationManager
But these classes are not recognized within my class library.
-
Charles Burns over 11 yearsThose parentheses need to be brackets.
-
Alaa over 11 years@CharlesBurns,Thanks, I wrote in VB by mistake, in C# sure it should be
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
-
Charles Burns over 11 yearsAhh, I didn't even realize that was VB. I thought it was a typo. In a way, my mistake too.
-
AechoLiu almost 10 yearsMSDN, System.configuration. It needs
System.Configuration.dll
. -
Mishax almost 10 years"Add a reference at the top of your code file" => that's a using directive, not a reference!
-
BJladu4 over 8 yearsIn Web project is better to use WebConfigurationManager in System.Web.Configuration.
-
Matt over 4 yearsAddition: Besides the indexer that accepts the name of the connection string, it is also allowed to use integer indices - which is useful if you want to read all connection strings in a
for
loop (for (int i = 0; i < numOfConnections; i++) { var conn = ConfigurationManager.ConnectionStrings[i]; ... }
) and make them selectable in a combobox. Withvar numOfConnections = ConfigurationManager.ConnectionStrings.Count;
you can determine how many connection strings exist. In this exampleconn.Name
contains the name of the connection.