In a web application, there is sometimes a need to store a read only string accessible throughout the project without having to access a database. An easy way to achieve this end goal is to create a key in the web.config file.

An advantage to adding a key to the appSettings of the web.config file is that the key will be accessible to all files in your project. Secondly, if this key should ever change, you can edit the key’s value without the need to recompile! Therefore, the value is semi-constant in that it doesn’t change during execution, but can be easily altered between builds. The key is added within appSettings of configuration in the web.config file.

<configuration>
<appSettings>
</appSettings>
<configuration>

Next is a simple example of how this can be used. Below is the relevant code sample of the web.config file.

<configuration>
<appSettings>
<add key =”supportEmailGroup” value=”support@victorchen.info”/>
</appSettings>
<configuration>

To access the key named supportEmailGroup, use the following code below. In the example below, the supportEmailGroup value is accessed in the code behind.

string supportEmailAddress = ConfigurationSettings.AppSettings[”supportEmailGroup”];

It is that easy. The web.config file can hold an arbitrary number of keys. I use the appSettings feature in every project. Some example of where this can be useful is pointing to file directory or connection strings.

This entry was posted on Monday, March 17th, 2008 at 4:53 pm and is filed under C#, Visual Studio. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses

  1. Basic User Login Impersonate on Trusted Network says

    […] of user impersonation includes a value key combination in the WebConfig file (to read an article on Store Constant Variables in WebConfig). The high level idea is to create two keys to control user login. One is of the debugger’s […]

  2. beastmoon says

    I adore this site! I can stay up all night just to have fun and see new posts. I love to spend my free time this way

Leave a Reply