Danny
Danny

Reputation: 107

Read connection string from web config

I am using Visual Studio 2012 and I am building a web application in Framework 4.5.
I want to save my connection string in the web config and to read from there.
For some reason i cant read it.
The web config

<connectionStrings>
    <add name="AdminConnection"     connectionString="DataSource=10.0.0.20;InitialCatalog=MailDB;PersistSecurityInfo=True;UserID=s      a;Password=********;"/>

The code

using System.Configuration;
string connectionString = System.Configuration.ConfigurationManager.AppSettings["AdminConnection"];

I am getting error on the configuration manager, and i tried all sort of variations. Thank for all.

Upvotes: 0

Views: 1968

Answers (3)

atlaste
atlaste

Reputation: 31146

ConfigurationManager.AppSettings is in your <appSettings> ; connection strings are in your ConfigurationManager.ConnectionStrings.

Upvotes: 0

Oded
Oded

Reputation: 499302

You should be using:

string connectionString = 
      ConfigurationManager.ConnectionStrings["AdminConnection"].ConnectionString;

Your code is trying to read from a non existing appSettings section, which is why you are getting errors.

The connectionStrings section in the configuration file gets deserialized into the ConnectionStrings collection, not into the AppSettings collection (the appSettings section gets deserialized into that).

Upvotes: 2

scottheckel
scottheckel

Reputation: 9244

That's not right. It's stored in your ConnectionStrings not your AppSettings. See the MSDN for How to: Read Connection Strings for more information.

Upvotes: 0

Related Questions