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

Source: Internet
Author: User

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.

Common Configuration file modes:

<configuration>
<configSections>//configuration section Declaration area, including configuration sections and namespace declarations
<section>//configuration section Declaration
<sectionGroup>//Define configuration section groups
Configuration section declarations in <section>//configuration section groups
<appSettings>//Pre-defined configuration section
<custom element 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>        <add key= " ConnectionString "value=" User source=.; Password=;initial catalog=test; Provider=SQLOLEDB.1; "/>        <add key=" 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.

Ii. ConfigurationManager class Reference methods in C #

C # added the Configuration, and later found no ConfigurationManager This class, later discovered: Although the reference to using System.Configuration; This package, but still does not work.

Finally, I found a solution, which is to find the class file in Solution Explorer, select "References", then right-click to select "Add Reference", and find system.configuration from. NET to add it to the OK

Third, 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 void Accessappsettings () {    //Get Configuration object    Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration (configurationuserlevel.none);    Read the value of the <add> element based on key    string name = Config. appsettings.settings["Name"]. Value;    Write the <add> element's value    config. appsettings.settings["Name"]. Value = "fx163";    Add <add> element    config. APPSETTINGS.SETTINGS.ADD ("url", "http://www.fx163.net");    Delete <add> element    config. AppSettings.Settings.Remove ("name");    Be sure to remember to save and write the config without parameters. Save () can also be    config. Save (configurationsavemode.modified);    Refresh, otherwise the program reads the previous value (possibly 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.

5, may have the reader to think, since the App. Config is the standard XML, of course, can also be used to manipulate the general XML file method to read and write. Of course it's possible! It's just that I think I lost the meaning of the VS Provisioning App. Config file, and it's easier to define a profile yourself.

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

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.