Sunday, January 13, 2013

How to add Custom Settings in the web.config File


ASP.NET also allows you to store your own settings in the web.config file, in an element called <appSettings>. Note that the <appSettings> element is nested in the root <configuration> element. Here’s the basic structure:

<?xml version="1.0" ?>
<configuration>
...
<appSettings>
<!-- Custom application settings go here. -->
</appSettings>
...
<system.web>
<!-- ASP.NET Configuration sections go here. -->
</system.web>
...
</configuration>

The custom settings that you add are written as simple string variables. You might want to use a special web.config setting for several reasons:

To centralize an important setting that needs to be used in many different pages: For example, you could create a variable that stores a database query. Any page that needs to use this query can then retrieve this value and use it.

To make it easy to quickly switch between different modes of operation: For example, you might create a special debugging variable. Your web pages could check for this variable and, if it’s set to a specified value, output additional information to help you test the application.

To set some initial values: Depending on the operation, the user might be able to modify these values, but the web.config file could supply the defaults.

You can enter custom settings using an <add> element that identifies a unique variable name (key) and the variable contents (value). The following example adds a variable that defines a file path where important information is stored:

<appSettings>
<add key="DataFilePath"
value="e:\NetworkShare\Documents\WebApp\Shared" />
</appSettings>

You can add as many application settings as you want, although this example defines just one.

You can create a simple test page to query this information and display the results, as shown in the following example (which is provided with the sample code as ShowSettings.aspx and ShowSettings.aspx.cs). You retrieve custom application settings from web.config by key name, using the WebConfigurationManager class, which is found in the System.Web.Configuration namespace. This class provides a static property called AppSettings with a collection of application settings.

using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
public partial class ShowSettings : System.Web.UI.Page
{
protected void Page_Load()
{
lblTest.Text = "This app will look for data in the directory:<br /><b>";
lblTest.Text += WebConfigurationManager.AppSettings["DataFilePath"];
lblTest.Text += "</b>";
}
}


No comments:
Write comments
Recommended Posts × +