6 out of 10 rated this helpful - Rate this topic

How to: Read Application Settings from the Web.config File

This example reads an application setting identified by the key customsetting1 from a Web.config file. The appSettings element is a NameValueCollection collection of strings. Working with collection elements can be slightly more complicated than working with other configuration elements.

To obtain configuration settings for the root-level Web configuration, null is passed to the OpenWebConfiguration method.

To update a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes. For additional code examples, see the AppSettingsSection class and related classes.

This example uses the non-static method of obtaining configuration data, which allows you to pull configuration data from any application. If you are going to obtain configuration information from the application in which your code resides, use the static method, which processes faster. For more information, see the Working with Local and Remote Configuration Settings section in ASP.NET Configuration API Overview.


			System.Configuration.Configuration rootWebConfig1 =
				System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
			if (rootWebConfig1.AppSettings.Settings.Count > 0)
			{
				System.Configuration.KeyValueConfigurationElement customSetting = 
					rootWebConfig1.AppSettings.Settings["customsetting1"];
				if (customSetting != null)
					Console.WriteLine("customsetting1 application string = \"{0}\"", 
						customSetting.Value);
				else
					Console.WriteLine("No customsetting1 application string");
			}


This example requires:

  • An appSettings element in the root Web.config file that looks like the following:

    <appSettings>
      <add key="customsetting1" value="Some text here"/>
    </appSettings>
    

    The appSettings element is a direct child of the <configuration> element and a peer of the system.web element.

Values read from the appSettings element of the Web.config file are always of type String. If the specified key does not exist in the Web.config file, no error occurs. Instead, an empty string is returned.

The configuration file should be protected on the server by using Windows security settings to limit who can read the file. Avoid storing sensitive information such as user credentials in the appSettings element of the Web.config file. Also consider encrypting configuration settings. For more information, see Encrypting Configuration Information Using Protected Configuration.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Minor error in robust programming
Under robust programming it says that an empty setting will return an empty string,  it will actually return a null string.

For completeness you might want to use String.isnullorempty to verify the contents,  if the parameter exists but is an empty string then you may still want to default it.
An example accessing \configuration\system.web\httpRuntime[maxQueryStringLength]

An example getting a specific node from the web.config file of the application.
This sample gets the MaxQueryStringLength value specified by the httpRuntime tag.

C#:
System.Configuration.Configuration webConfig;
System.Web.Configuration.HttpRuntimeSection webConfig_HttpRuntime; //This will hold the httpRuntime element located in web.config at /configuration/system.web (aka <configuration><system.web>)
int MaxQueryStringLength;

webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
webConfig_HttpRuntime = webConfig.GetSection("system.web2/httpRuntime");
MaxQueryStringLength = webConfig_HttpRuntime != null ? webConfig_HttpRuntime.MaxQueryStringLength - 2 : 2048;

VB:
Dim webConfig As System.Configuration.Configuration
Dim webConfig_HttpRuntime As Web.Configuration.HttpRuntimeSection    'This will hold the httpRuntime element located in web.config at /configuration/system.web (aka <configuration><system.web>)
Dim MaxQueryStringLength As Integer

webConfig  = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath)
webConfig_HttpRuntime = webConfig.GetSection("system.web2/httpRuntime")
MaxQueryStringLength  = If(webConfig_HttpRuntime IsNot Nothing, webConfig_HttpRuntime.MaxQueryStringLength - 2, 2048)

Thanks to awiserm74 for ApplicationPath, I had forgotten about that.

May not work unless the application path is specified when calling OpenWebConfiguration
The code in the example did not work on my dev box.  I needed to pass the application path to OpenWebConfiguration in order to get a configuration object that contained the appSettings from my web.config file.

Example:
                string configPath = HttpContext.Current.Request.ApplicationPath;
                System.Configuration.Configuration webConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
Best handling of an AppSettings key
Not good to do it in one line since someone could delete your key from the web.config (which could throw a nullReferenceException). 
Best to do it in 2 steps, seeing if ".ToString()" has anything in it, and then sending your output to string, which you can convert/parse
if you need to.  This example gets a "refreshValue" for a Timer object:

        int valTimerFreq = 0;
        if (int.Parse(ConfigurationManager.AppSettings["refreshValue"].ToString()) > 0)
            valTimerFreq = int.Parse(ConfigurationManager.AppSettings["refreshValues"].ToString() + "000");
        Timer1.Interval = valTimerFreq;
Concise example
You can read a setting from web.config in one line as follows:
string value = System.Web.Configuration.WebConfigurationManager.AppSettings["Key"];