Export (0) Print
Expand All

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.

Example

No code example is currently available or this language may not be supported.

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.

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.

Security

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

Community Additions

ADD
Show:
© 2014 Microsoft