Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the connectionstring in .net 4

I want to get a connection string from the app.config file.

connectionString = System.Configuration.ConfigurationSettings.AppSettings["DBEntities"];

But it doesn't work. It's empty.

I cannot access the System.Configuration.ConfigurationManager because it's .NET 4. How can I get my connection string from the app.config?

like image 954
CoffeeCode Avatar asked Oct 15 '10 10:10

CoffeeCode


People also ask

Where do I put ConnectionString in web config?

config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.

How do you read a connection string?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

Where are connectionStrings stored?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove. The following configuration file fragment demonstrates the schema and syntax for storing a connection string.


2 Answers

Use

string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;  

Make sure to add reference to System.configuration in your project.

like image 111
sh_kamalh Avatar answered Sep 23 '22 02:09

sh_kamalh


In .net 4 you have to use:

ConfigurationManager.ConnectionStrings["name of connection string in web.config"] 

More about it is here and here.

like image 29
Nealv Avatar answered Sep 21 '22 02:09

Nealv