Configuration file read/write

Source: Internet
Author: User

The system. configurationmanager class is used to read configuration files. Its members are as follows:

I. deleettings

Appsetting is the simplest configuration section, and reading and writing is very simple.

Name Description
Appsettings Obtains the appsettingssection data configured by default for the current application.
Connectionstrings Obtains the connectionstringssection data configured by default for the current application.

 

<?xml version="1.0" encoding="utf-8" ?><configuration>  <appSettings>    <add key="DB" value="Access" />  </appSettings>  <connectionStrings>    <add name="connstr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\C#Code\DBOperation\ykjj.mdb"/>  </connectionStrings></configuration>

Example:

Class program {static void main (string [] ARGs) {string strpolicettings = system. configuration. configurationmanager. appsettings ["DB"]; // obtain the value through the attribute index console. writeline (strpolicettings); string strconnection = system. configuration. configurationmanager. connectionstrings ["connstr"]. tostring (); console. writeline (strconnection); console. readkey ();}}

  

For the above appsettings and connectionstrings, both attributes are read by the configurationmanager. Generally, most configuration information can be stored in the deleettings. However, if you think it is not enough, you can use custom configuration information.

Ii. Custom configuration section

  1. Handler

In the custom configuration section, configuration provides many handler classes for you to choose from. Even if you don't think it is enough, you can customize handler processing.
Let's first learn how to use three simple handler:

  • System. configuration. namevaluesectionhandler
  • System. configuration. dictionarysectionhandler
  • System. configuration. singletagsectionhandler

Sample configuration file code:

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <section name = "person" type = "system. configuration. namevaluesectionhandler"/> <! -- Return the information in the configuration section in the form of namevalue key value/pair --> <section name = "man" type = "system. configuration. dictionarysectionhandler"/> <! -- Return the information in the configuration section in the form of a dictionary key-value pair --> <section name = "name" type = "system. configuration. singletagsectionhandler"/> <! -- Infrastructure. Process the configuration sections in the. config file represented by a single XML tag. --> </Configsections> <person> <add key = "" value = ""/> <add key = "" value = "Guan Yu"/> <add key = "laosan" value = "Zhang Fei"/> </person> <man> <add key = "boss" value = "Cao"/> <add key = "" Value = "dianwei"/> <add key = "laosan" value = "guo jia"/> </man> <name one = "1" Two = "2" Three = "3 "Four =" 4 "Five =" 5 "/> <! -- Note that a single singletagsectionhandler can be processed, but no matter how many singletagsectionhandler can be processed. --> </configuration>

Sample Code for reading:

Static void main (string [] ARGs) {// read name namevaluecollection NVC = (namevaluecollection) configurationmanager. getsection ("person"); foreach (string key in NVC. allkeys) {console. writeline (Key + ":" + NVC [Key]);} // read man idictionary dict = (idictionary) configurationmanager. getsection ("man"); foreach (string key in dict. keys) {console. writeline (Key + ":" + dict [Key]);} idictionary dict1 = (idictionary) configurationmanager. getsection ("name"); foreach (string key in dict1.keys) {console. writeline (Key + ":" + dict1 [Key]);} console. readkey ();}

The output result is as follows:

  

  2. Custom Handler

The custom read node must implement the iconfigurationsectionhandler interface and provide the specific implementation of create.

Appconfig code:

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <! -- The following type is the location where the processing node personhandler is located. The second parameter is the Assembly. You can skip this parameter after version --> <section name = "person" type = "leleapplication1.personhandler, leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "allowlocation =" true "allowdefinition =" everywhere "/> </configsections> <person age =" 23 "name =" Liu Bei "/> </configuration>

Main program code:

Class program {static void main (string [] ARGs) {hashtable Config = configurationmanager. getsection ("person") as hashtable; console. writeline ("number of nodes:" + config. count); // two key-value pairs, where dekey can be converted into a hashtable foreach (dictionaryentry dekey in config) {console. writeline ("attribute element:" + dekey. key. tostring (); hashtable attribs = (hashtable) dekey. value; foreach (dictionaryentry deattrib in attribs) {consol E. writeline (deattrib. key. tostring () + "=" + deattrib. value. tostring () ;}} console. readkey () ;}}// note that you must implement the iconfigurationsectionhandler Interface Class personhandler: iconfigurationsectionhandler {public object create (Object parent, object configcontext, system. XML. xmlnode section) {hashtable myconfig = new hashtable (); // any attributes obtained from this section element. Hashtable myattribs = new hashtable (); // traverses the attributes of the current node foreach (xmlattribute attrib in section. attributes) {// if the current node is an attribute node, add it to myattribs if (xmlnodetype. attribute = attrib. nodetype) {myattribs. add (attrib. name, attrib. value) ;}} // Add the set of current attribute nodes to myconfig. add (section. name, myattribs); Return myconfig ;}}

The output result is as follows:

  

This configuration code seems a little difficult. After all, there are two layers of hashtable.

  3. Reading Property

  1. To use this method, you need to customize a class and inherit from the configurationsection base class. The name string passed in the configurationproperty constructor will be used in the config file to indicate the property names of each parameter.
  2. This [] or base [] is called to read and write attribute values, which are saved by the base class. Do not design fields to save them.
  3. To use the configuration node for resolution, you must register in <configsections>: <section name = "person" type = "leleapplication1.personsection, leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "allowlocation =" true "allowdefinition =" everywhere "/>. Note that name =" person "must be consistent with <person...> is corresponding.

Let's take a look at the Configuration File Syntax:

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <! -- The following type is the location where the processing node personsection is located. The second parameter is the Assembly. You can skip this parameter after version --> <section name = "person" type = "leleapplication1.personsection, leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "allowlocation =" true "allowdefinition =" everywhere "/> </configsections> <person age =" 23 "name =" Liu Bei "/> </configuration>

Then the program code:

Class program {static void main (string [] ARGs) {personsection person = configurationmanager. getsection ("person") as personsection; console. writeline ("name = {0}, age = {1}", person. age, person. name); console. readkey () ;}// note that this is inherited from system. configuration. configurationsection specifies the class personsection: system. configuration. configurationsection {[configurationproperty ("Age", isrequired = false, defaultvalue = 0)] public int age {get {return (INT) base ["Age"];} set {base ["Age"] = value;} [configurationproperty ("name", isrequired = false, defaultvalue = "")] public string name {get {return (string) base ["name"] ;}set {base ["name"] = value ;}}}

The output result is as follows:

  

  4. Configure child elements

For a slightly more complex structure,The model class of the child element must inherit from the configurationelement.

Config File Code:

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <section name = "complex" type = "leleapplication1.complexsection, consoleapplication1 "/> </configsections> <complex Height =" 182 "> <child firstname =" Zhang "lastname =" "/> </complex> </configuration>

Main program code:

Class program {static void main (string [] ARGs) {complexsection sec = configurationmanager. getsection ("complex") as complexsection; console. writeline (sec. height); // access the property console. writeline (sec. child. firstname); // access the subnode Attribute Console. writeline (sec. child. lastname); // access the subnode Attribute Console. readkey () ;}} public class complexsection: configurationsection {[configurationproperty ("height", isrequired = true)] public int height {get {return (INT) base ["height"] ;}set {base ["height"] = value ;}} [configurationproperty ("child", isdefaultcollection = false)] public childsection child {get {return (childsection) base ["child"] ;}set {base ["child"] = value ;}} public class childsection: configurationelement {[configurationproperty ("firstname", isrequired = true, iskey = true)] Public String firstname {get {return (string) base ["firstname"];} set {base ["firstname"] = value ;}} [configurationproperty ("lastname", isrequired = true)] Public String lastname {get {return (string) base ["lastname"] ;}set {base ["lastname"] = value ;}}}

Output result:

  

  5. CDATA in the configuration file

Sometimes, the configuration file may contain some complicated code segments, and xml cdata is used at this time.

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <section name = "mysection" type = "leleapplication1.mysection, consoleapplication1"/> </configsections> <mysection> <HTML> <! [CDATA [<Div style = "# font-size: 24px"> bold display </div>]> 

The main program code is as follows:

Namespace consoleapplication1 {class program {static void main (string [] ARGs) {mysection section = configurationmanager. getsection ("mysection") as mysection; console. writeline ("{0} {1}", section. HTML. commandtext, section. SQL. commandtext); console. readkey () ;}// note that this is inherited from system. configuration. configurationsection: Class mysection: system. configuration. configurationsection {[configurationproperty ("Html", isrequired = false)] public mytextelement HTML {get {return (mytextelement) base ["html"];} set {base ["html"] = value;} [configurationproperty ("SQL", isrequired = false)] public mytextelement SQL {get {return (mytextelement) base ["SQL"] ;}set {base ["SQL"] = value ;}} public class mytextelement: configurationelement {protected override void deserializeelement (system. XML. xmlrea Der reader, bool serializecollectionkey) {commandtext = reader. readelementcontentas (typeof (string), null) as string;} protected override bool serializeelement (system. XML. xmlwriter writer, bool serializecollectionkey) {If (writer! = NULL) {writer. writecdata (commandtext);} return true;} [configurationproperty ("data", isrequired = false)] Public String commandtext {get {return this ["data"]. tostring () ;}set {This ["data"] = value ;}}}}

The output is as follows:

  

  6. Configure element collection

Similar to the following configuration method, it is too common in httphandler and httpmodule of ASP. NET.

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <section name = "mysection" type = "leleapplication1.mysection, consoleapplication1 "/> </configsections> <mysection> <add key =" A "value =" Liu Bei "> </Add> <add key =" B "value =" Guan Yu"> </Add> <add key = "C" value = "Zhang Fei"> </Add> </mysection> </configuration>

The implementation code is as follows:

Class program {static void main (string [] ARGs) {mysection section = configurationmanager. getsection ("mysection") as mysection; foreach (mykeyvaluesetting add in section. keyvalues) {console. writeline (Add. key + ":" + Add. value);} console. readkey () ;}} public class mysection: configurationsection // select this base class for all configuration nodes {Private Static readonly configurationproperty s_property = new configurationprop Erty (string. empty, typeof (mykeyvaluecollection), null, configurationpropertyoptions. isdefaultcollection); [configurationproperty ("", Options = configurationpropertyoptions. isdefaultcollection)] public mykeyvaluecollection keyvalues {get {return (mykeyvaluecollection) base [s_property] ;}} [configurationcollection (typeof (mykeyvaluesetting)] public class mykeyvaluecollection: configurationeleme Ntcollection // customize a set {// basically, all methods can simply call the implementation of the base class. Public mykeyvaluecollection (): Base (stringcomparer. ordinalignorecase) // ignore the case {} // The key is the index. But it also calls the implementation of the base class, just do the type conversion. New public mykeyvaluesetting this [string name] {get {return (mykeyvaluesetting) base. baseget (name) ;}// the abstract classes in the following two methods must be implemented. Protected override configurationelement createnewelement () {return New mykeyvaluesetting ();} protected override object getelementkey (configurationelement element) {return (mykeyvaluesetting) element ). key;} // Note: if you do not need to modify the set in the code, you do not need to add, clear, remove public void add (mykeyvaluesetting setting) {This. baseadd (setting);} public void clear () {base. baseclear ();} public void remove (string name) {base. baseremove (name) ;}} public class mykeyvaluesetting: each element in the configurationelement // set {[configurationproperty ("key", isrequired = true)] public String key {get {return this ["key"]. tostring () ;}set {This ["key"] = value ;}} [configurationproperty ("value", isrequired = true)] public String Value {get {return this ["value"]. tostring () ;}set {This ["value"] = value ;}}}

The output is as follows:

  

Summary:

1. Create a derived class inherited from configurationelement for the parameter items in each set.
2. Create a collection class inherited from configurationelementcollection for the collection. Specifically, the method of the base class is called.
3. When creating an inherited class of configurationsection, you can create an attribute that represents the set. Pay attention to the parameters of [configurationproperty.

  7. Configure node write

An example of writing a configuration node is as follows:

Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. none); personsection section = config. getsection ("person") as personsection; section. name = ""; section. age = 10000; config. save (); configurationmanager. refreshsection ("person"); // validate the modified result

Before modifying the configuration node, we need to call configurationmanager. openexeconfiguration (), and then call config. after obtaining the node, getsection () is converted to the node type we defined. Then, you can modify the parameter items defined by using the strong type method, and finally call config. save.

Note:

  1. . To optimize the read operations on the configuration node, the data will be cached. If you want to use the modified results to take effect, you also need to call configurationmanager. refreshsection ("..... ").
  2. To modify web. config, use webconfigurationmanager.

  8. Read the nodes defined in. NET Framework.

It is easy to read the. NET Framework defined nodes:

  <system.web>    

The main program is as follows:

public ActionResult Index()    {        HttpModulesSection section = ConfigurationManager.GetSection("system.web/httpModules") as HttpModulesSection;        foreach (HttpModuleAction action in section.Modules)        {            Response.Write(action.Name + "<br/>");        }        return Content("");    }

The output is as follows:

  

Note that the configurations in mechine on the server are read together.

In web. config, it is read-only and cannot be written, but not in the same way as in the preceding example.

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.