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 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 themethod.
To update a configuration setting, use theor method of the configuration object. For more information, see . For additional code examples, see the 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.
Compiling the Code
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.