How C # reads and writes the app. config configuration file

Source: Internet
Author: User

We often want to write some configuration information in the program, such as the version number, the connection string for the database, and so on. You may know that you can use Properties.settings to do similar work in WinForm applications, but these actually take advantage of the app. config profile.

This article explores how to access the app. Config method in code. The use of App. Config is far more complex than the one mentioned above, so only the most basic AppSettings configuration section is discussed.

Overview of configuration files:

The application configuration file is a standard XML file, and XML tags and attributes are case-sensitive.

It can be changed as needed, and developers can use the configuration file to change the settings without having to recompile the application.

The root node of the profile is the configuration file. We often visit appsettings, which is made up of. NET pre-defined configuration section. The schema of the configuration file that we often use is the form of customer complaint.

First of all, there is an impression that the following example will have a clearer understanding. The following "configuration section" can be understood as a node that configures an XML.

<Configuration><configsections>//configuration section Declaration area, including configuration section and namespace declaration< Section>//configuration section declaration<sectiongroup>//Define configuration section groups< Section>configuration section declarations in the//configuration section group<appSettings>//Pre-defined configuration section<Customelement for configuration section>Configuration section Settings area

The following is an example of the most common application configuration file, with only the appsettings section:

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>    <appSettings>      <AddKey= "ConnectionString"value= "User source=.; Password=;initialcatalog=test; Provider=SQLOLEDB.1; " />      <AddKey= "TemplatePath"value= "Template" />    </appSettings></Configuration>

In the predefined appSettings section (note case), there are many elements, the names of which are "add", and two attributes are "key" and "value" respectively.

. NET provides access to the appsettings section. In. NET 1.0 and 1.1, you can use the system.configuration.configurationsettings.appsettings["key" to Val the <add> element of key = "Key" The UE attribute is accessed.

Note : It is now clear in the. Net FrameWork 2.0 that this configurationsettings property has been deprecated and it is recommended to change to ConfigurationManager or WebConfigurationManager.

With System.Configuration.ConfigurationManager, you need to add a reference to the System.Configuration.dll assembly in your project. (Right-click the project name in the Solution Manager and select Add Reference from the right-click menu, located under the. NET tab.) )

Once you have added a reference, you can use configurationmanager.appsettings["Key" to read the corresponding value.

However, the Configurationmanager.appsettings property is read-only and does not support modifying property values. This is because it is said that Microsoft does not recommend that we write the app. Config file dynamically, but instead recommends that you configure it manually to make static access when the program is running.

If you really need to make changes in your program, write app. config, please look down.

Second, read and write operation of appsettings configuration section

The method of reading the AppSettings section of the App. Config file is relatively simple and can be accessed by means of the system.configuration.configurationmanager.appsettings["Key" above. But it has been said earlier that the method does not provide writing.

If you want to write to a configuration file, you can use the ConfigurationManager object to perform an open profile operation, and a configuration object will be returned, which can be manipulated by using the object (and so on).

The implementation code is given below (adding a reference using the System.Configuration namespace)

Private voidaccessappsettings () {//get the Configuration objectConfiguration config =System.Configuration.ConfigurationManager.OpenExeConfiguration (Configurationuserlevel.none); //read the value of the <add> element according to key    stringname = CONFIG. appsettings.settings["name"].  Value; //write the value of the <add> elementConfig. appsettings.settings["name"]. Value ="Zcl"; //Add <add> elementsConfig. APPSETTINGS.SETTINGS.ADD ("Name",the Config");  //Delete <add> elementsConfig. AppSettings.Settings.Remove ("name"); //Be sure to remember to save and write the config without parameters. Save () can also    CONFIG.  Save (configurationsavemode.modified); //Refresh, otherwise the program reads the previous value (may have been loaded into memory)System.Configuration.ConfigurationManager.RefreshSection ("appSettings");}

It is important to note that:

1. Accessing the <add> element based on a nonexistent key value, or even removing the nonexistent element using the Remove () method, will not cause an exception, which returns NULL.

2, add already existing <add> elements will not cause an exception, but concat the existing value and the new value, with "," separated, for example: "Olldvalue,newvalue".

3, after the project is compiled, under the running directory Bin\debuge file, there will be two configuration files, one named "ProjectName.EXE.config" and the other named "ProjectName.vshost.exe.config". The first file is the configuration file that the project is actually using, and the changes made in the program run will be saved here, and the second file is actually the sync file for "app. Config" in the original code and will not change during the program's run.

4, pay special attention to case (XML file is case-sensitive), such as appsettings configuration section.

How C # reads and writes the app. config configuration file

Related Article

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.