C # parse the configuration file content system. Configuration

Source: Internet
Author: User
1. Create a configuration section class
You must create an object inherited from the configurationsection to perform configuration data read and write operations. The configurationsection provides an indexer for obtaining and setting configuration data. Note that attributes with the configurationproperty feature will be stored, and the names must be case-insensitive. In the following code, all "IDS" must be the same.
Class configsectiondata: configurationsection
{
[Configurationproperty ("ID")]
Public int ID
{
Get {return (INT) This ["ID"];}
Set {This ["ID"] = value ;}
}

[Configurationproperty ("time")]
Public datetime time
{
Get {return (datetime) This ["time"];}
Set {This ["time"] = value ;}
}
}

2. Create a configuration file operation object
Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. None );

Configsectiondata DATA = new configsectiondata ();
Data. ID = 1000;
Data. Time = datetime. now;

Config. Sections. Add ("add", data );
Config. Save (configurationsavemode. Minimal );

The above example is to operate app. config and write configuration data named "add" under the root node (configuration.
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section name = "add" type = "leleapplication1.configsectiondata,.../>
</Configsections>
<Add id = "1000" time = "02/18/2006 21:51:06"/>
</Configuration>

Note that vs2005 writes information to * .vshost.exe in IDE mode. and overwrite the file when the program is closed. Therefore, you may not be able to see the configuration data you have written, as long as you execute * in resource management *. in *. EXE. the result is displayed in the config file.

To operate non-default configuration files, you can use the execonfigurationfilemap object.
Execonfigurationfilemap file = new execonfigurationfilemap ();
File. execonfigfilename = "test. config ";
Configuration Config = configurationmanager. openmappedexeconfiguration (file, configurationuserlevel. None );

Configsectiondata DATA = new configsectiondata ();
Data. ID = 1000;
Data. Time = datetime. now;

Config. Sections. Add ("add", data );
Config. Save (configurationsavemode. Minimal );

If you do not want to write configuration data under the root node, you can use the configurationsectiongroup object.
Execonfigurationfilemap file = new execonfigurationfilemap ();
File. execonfigfilename = "test. config ";
Configuration Config = configurationmanager. openmappedexeconfiguration (file, configurationuserlevel. None );

Configsectiondata DATA = new configsectiondata ();
Data. ID = 1000;
Data. Time = datetime. now;

Config. sectiongroups. Add ("group1", new configurationsectiongroup ());
Config. sectiongroups ["group1"]. Sections. Add ("add", data );

Config. Save (configurationsavemode. Minimal );

The following is the generated configuration file.
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Sectiongroup name = "group1" type = "system. configuration. configurationsectiongroup,...>
<Section name = "add" type = "leleapplication1.configsectiondata,.../>
</Sectiongroup>
</Configsections>
<Group1>
<Add id = "1000" time = "02/18/2006 22:01:02"/>
</Group1>
</Configuration>

3. Read the configuration file
Execonfigurationfilemap file = new execonfigurationfilemap ();
File. execonfigfilename = "test. config ";
Configuration Config = configurationmanager. openmappedexeconfiguration (file, configurationuserlevel. None );

Configsectiondata DATA = config. sectiongroups ["group1"]. Sections ["add"] As configsectiondata;
// Configsectiondata DATA = config. Sections ["add"] As configsectiondata; // read from the root node

If (Data! = NULL)
{
Console. writeline (data. ID );
Console. writeline (data. time );
}

4. Write the configuration file

Before writing to the configurationsectiongroup and configurationsection, you must determine whether the configuration with the same name already exists. Otherwise, the writing will fail.
In addition, if the configuration file is modified by another configuration object, saving fails and an exception is thrown. Singleton mode is recommended.
Execonfigurationfilemap file = new execonfigurationfilemap ();
File. execonfigfilename = "test. config ";
Configuration Config = configurationmanager. openmappedexeconfiguration (file, configurationuserlevel. None );

Configsectiondata DATA = new configsectiondata ();
Data. ID = 2000;
Data. Time = datetime. now;

Configurationsectiongroup group1 = config. sectiongroups ["group1"];
If (group1 = NULL)
Config. sectiongroups. Add ("group1", new configurationsectiongroup ());

Configurationsection DATA = group1.sections ["add"] As config;
If (add = NULL)
Config. sectiongroups ["group1"]. Sections. Add ("add", data );
Else
{
Group1.sections. Remove ("add ");
Group1.sections. Add ("add", data );

// Or directly modify the original configuration object, provided that the type conversion is successful.
// Configsectiondata configdata = add as configsectiondata;
// Configdata. ID = data. ID;
// Configdata. Time = data. time;
}

Config. Save (configurationsavemode. Minimal );

5. Delete configuration section
Delete configurationsectiongroup
Config. sectiongroups. Remove ("group1 ");
// Config. sectiongroups. Clear ();

Config. Save (configurationsavemode. Minimal );

Delete configurationsection
Config. Sections. Remove ("Add1 ");
// Config. Sections. Clear ();

If (config. sectiongroups ["group1"]! = NULL)
{
Config. sectiongroups ["group1"]. Sections. Remove ("Add2 ");
// Config. sectiongroups ["group1"]. Sections. Clear ();
}

Config. Save (configurationsavemode. Minimal );

6. Miscellaneous
You can use configurationmanager. openmachineconfiguration () to operate the machine. config file.
You can also use the webconfigurationmanager class in the system. Web. Configuration namespace to operate the Asp.net configuration file.
Configurationmanager also provides convenient operations such as deleettings, connectionstrings, and getsection.

7. Use custom classes
You can use a custom class, but you need to define a converter.
Using system;
Using system. collections;
Using system. Collections. Generic;
Using system. configuration;
Using system. Globalization;
Using system. componentmodel;

// The Custom class to write the configuration file
Class customdata
{
Public customdata (string S)
{
This. S = s;
}

Private string S;
Public String s
{
Get {return s ;}
Set {S = value ;}
}
}

// Custom converter (the Demo code ignores the type judgment)
Class customconvert: configurationconverterbase
{
Public override bool canconvertfrom (itypedescriptorcontext CTX, type)
{
Return (type = typeof (string ));
}

Public override object Convertor (itypedescriptorcontext CTX, cultureinfo CI, object value, type)
{
Return (value as customdata). S;
}

Public override object convertfrom (itypedescriptorcontext CTX, cultureinfo CI, object data)
{
Return new customdata (string) data );;
}
}

Class configsectiondata: configurationsection
{
[Configurationproperty ("ID")]
Public int ID
{
Get {return (INT) This ["ID"];}
Set {This ["ID"] = value ;}
}

[Configurationproperty ("time")]
Public datetime time
{
Get {return (datetime) This ["time"];}
Set {This ["time"] = value ;}
}

[Configurationproperty ("Custom")]
[Typeconverter (typeof (customconvert)] // specifies the converter
Public customdata custom
{
Get {return (customdata) This ["Custom"];}
Set {This ["Custom"] = value ;}
}
}

Public class Program
{
Static void main (string [] ARGs)
{
Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. None );

Configsectiondata DATA = new configsectiondata ();
Data. ID = 1000;
Data. Time = datetime. now;
Data. Custom = new customdata ("abcdefg ...");

Config. Sections. Add ("add", data );
Config. Save (configurationsavemode. Minimal );

// Read Test
Configsectiondata configdata = (configsectiondata) config. Sections ["add"];
Console. writeline (configdata. Custom. s );
}
}

Saved configuration file
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section name = "add" type = "..."/>
</Configsections>
<Add id = "1000" time = "04/17/2006 22:06:58" Custom = "abcdefg..."/>
</Configuration>

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.