How to use the ConfigurationManager.AppSettings

jorame picture jorame · Aug 15, 2011 · Viewed 164.9k times · Source

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.

Answer

Justin Rusbatch picture Justin Rusbatch · Aug 15, 2011

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"]);