Posts Tagged ‘appSettings’

Store Constant Variables in WebConfig

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.