. Net2.0 use ConfigurationManager to read and write configuration files

Source: Internet
Author: User
Tags config modify

. net1.1 a profile management class is typically encapsulated in a project to read and write if it is not convenient to have flexible operations and read and write configuration files. Using ConfigurationManager and WebConfigurationManager classes in. net2.0 can be a good management configuration file, The ConfigurationManager class is in System.Configuration, WebConfigurationManager in System.Web.Configuration. As explained by MSDN, for WEB application configuration, it is recommended that you use the System.Web.Configuration.WebConfigurationManager class instead of using the System.Configuration.ConfigurationManager class.

Let me give you a simple example of how to use the WebConfigurationManager operation configuration file:

Open configuration file
Configuration config = webconfigurationmanager.openwebconfiguration ("~");
Get appsettings node
Appsettingssection appsection = (appsettingssection) config. GetSection ("appSettings");
Adding elements to the appsettings node
APPSECTION.SETTINGS.ADD ("Addkey1", "Key1 ' s Value");
APPSECTION.SETTINGS.ADD ("Addkey2", "Key2 ' s Value");
Config. Save ();

You can see changes in the configuration file after you run the code:

<appSettings>
<add key= "Addkey1" value= "Key1 ' s value"/>
<add key= "Addkey2" value= "Key2 ' s value"/>
</appSettings>

It is also convenient to modify and delete nodes or properties:

Open configuration file
Configuration config = webconfigurationmanager.openwebconfiguration ("~");
Get appsettings node
Appsettingssection appsection = (appsettingssection) config. GetSection ("appSettings");
Delete elements from the appsettings node
AppSection.Settings.Remove ("Addkey1");
Modifying elements in the appsettings node
appsection.settings["Addkey2"]. Value = "Modify key2 ' s value";
Config. Save ();

Configuration file:

<appSettings>
<add key= "Addkey2" value= "Modify key2 ' s value"/>
</appSettings>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.