Coder Perfect

Read connection string from web.config

Problem

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

These classes, however, aren’t found in my library of classes.

Asked by chamara

Solution #1

You must first create a reference to System.Configuration, after which you must use:

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

Answered by Muhammad Akhtar

Solution #2

Assign the reference to System.Configuration.

It’s not included by default for some strange reason.

Answered by peteisace

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

Answered by MDM

Solution #4

After that, add System.Configuration as a reference:

 using System.Configuration;

 ...

 string conn = 
    ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

Answered by nirmus

Solution #5

You should probably add a reference to the System. If it hasn’t previously been done, add the configuration assembly.

You might also want to add the following line to the top of your code file:

using System.Configuration;

Answered by Akram Shahda

Post is based on https://stackoverflow.com/questions/6134359/read-connection-string-from-web-config