Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the ConfigurationManager.AppSettings

I've never used the "appSettings" before. How do you configure this in C# to use with a SqlConnection, this is what I use for the "ConnectionStrings"

SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 

And this is what I have for the "appSettings"

SqlConnection con = new SqlConnection(); con = ConfigurationManager.AppSettings("ConnectionString"); 

but it is not working.

like image 532
jorame Avatar asked Aug 15 '11 19:08

jorame


People also ask

What is the use of ConfigurationManager AppSettings?

Gets the AppSettingsSection data for the current application's default configuration.

How do I access AppSettings in C#?

To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.

What is the use of ConfigurationManager in C#?

The ConfigurationManager class enables you to access machine, application, and user configuration information. This class replaces the ConfigurationSettings class, which is deprecated. For web applications, use the WebConfigurationManager class.


1 Answers

Your web.config file should have this structure:

<configuration>     <connectionStrings>         <add name="MyConnectionString" connectionString="..." />     </connectionStrings> </configuration> 

Then, to create a SQL connection using the connection string named MyConnectionString:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString); 

If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

<configuration>     <appSettings>         <add key="MyConnectionString" value="..." />     </appSettings> </configuration> 

And then your SqlConnection constructor would look like this:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]); 
like image 57
Justin Rusbatch Avatar answered Sep 22 '22 19:09

Justin Rusbatch