How to: Read Application Settings from the Web.config File
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

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 =
if (0 < rootWebConfig1.AppSettings.Settings.Count)
    System.Configuration.KeyValueConfigurationElement customSetting = 
    if (null != customSetting)
        Console.WriteLine("customsetting1 application string = \"{0}\"", 
        Console.WriteLine("No customsetting1 application string");

Compiling the Code

This example requires:

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

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

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

Robust Programming

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.

See Also

© 2015 Microsoft