ASP.NET 3.5 – How to access web.config AppSettings and ConnectionStrings from the code.

Please note that this article applies to the ASP.NET 2.0 framework and later. With the ASP.NET 2.0 configuration API, there is a new way to retrieve AppSettings and ConnectionString sections from web.config in the ASP.NET applications. New ConfigurationManager class allows you to access configuration files and replaces the ASP.NET 1.x’s ConfigurationSettings class, which is deprecated.

You can use the ConfigurationManager API’s AppSettings and ConnectionStrings classes to access pre-defined web.config appSettings and connectionStrings sections respectively.

1. Sample Web.Config section with a Appsettings:

<script>
<appSettings>
<add key=”XMLPath” value=”~/testXML.xml”/>
</appSettings>
<script>

Now lets get the xml path from the Web.Config file with only one line of code:
string xmlPath = ConfigurationManager.AppSettings [“XMLPath” ];

2. Sample Web.Config section with a ConnectionString:

<connectionStrings>
<remove name=”LocalSqlServer” />
<add name=”LocalSqlServer” connectionString=”Data Source=myDBServer;database=myDB;Integrated Security=True;” providerName=”System.Data.SqlClient”/>
</connectionStrings>

Now lets get the ConnectionString from the Web.Config file with only one line of code:
string strConnString = ConfigurationManager.ConnectionStrings[“LocalSqlServer”].ConnectionString;

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s