Configuration File AppSettings - High-Flying C# Coding Tips


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Configuration File AppSettings

On this page we'll look at how to store and retrieve values in a configuration file such as the Web.Config file.

You can store text values in an application's configuration file, for instance all .NET Web Applications have a Web.Config file.  Storing values in the configuration file has certain advantages such as if you want a variable to be global across your application, such as a global setting for the number of items which appears in a list, a site wide name or some other value which you want to store in a central location which can be called on by any of the pages.  This leads to another advantage in that it is easier to change the value of a variable contained in the configuration file, in that you can simply edit the Web.Config file using Notepad, change the file and Save, and then the Web Application uses the new value.  This is apposed to storing the value in compiled code, requiring the application to be rebuilt and deployed for the change to take place.

You don't however want to start putting lots of variables into the Web.Config file, only if there is a particular need to, such as one of the advantages just mentioned.

How to store values in a configuration file

So to put a value into the configuration file, you store it in the <appSettings/> section of the configuration file, using the <add key="Variable-Name" value="Variable-Value"/> key / value pair syntax.


<?xml version="1.0"?>
<configuration>
...
 <appSettings>
  <add key="CompanyName" value="DemoName" />
 </appSettings>


How to retrieve values stored in a configuration file

With the above value stored in the Web.Config file, you can then use the ConfigurationManager.AppSettings.Get("Variable-Name") to return a string representation of your value stored in the configuration file.  You'll need to reference the System.Configuration namespace to gain access to the ConfigurationManager class.


using System.Configuration;
...



// get the value from the web.config file
string _companyName = "";
_companyName = ConfigurationManager.AppSettings.Get("CompanyName");


Finally, as the configuration file is an XML file, using certain characters can cause issues if they're not compliant with XML standards.