Read connection string from web.config

chamara picture chamara · May 26, 2011 · Viewed 411.1k times · Source

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.

Answer

Muhammad Akhtar picture Muhammad Akhtar · May 26, 2011

You need to add a reference to System.Configuration and then use:

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