Read and write Config,xml configuration file

Source: Internet
Author: User
Tags cdata

Respect Original: Http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html#_labelStart

Talk today about the various ways to read and write config files in. net. In this blog, I'll explain the read and write operations for various profiles. Because the content is more intuitive, so there is not too much empty truth, only real demo code, the purpose is only to reproduce the actual development of the various scenes. I hope you can enjoy it.

Usually, we're in. NET development process, you will be exposed to two types of configuration files: Config files, XML files. Today's blog examples will also describe the various operations of these two categories of profiles. In the config file, I will mainly demonstrate how to create my own custom configuration node, rather than how to use appsetting.

Please note: The config file referred to in this article refers specifically to app.config or web.config, rather than to a generic XML file. In this type of configuration file, because the. NET Framework has defined some configuration nodes for them, we cannot simply read and write it in a serialized way.

Config file-Custom configuration node

Why you want to customize the configuration node.
Indeed, there are a lot of people who use config files directly using appsetting, and all of the configuration parameters are plugged in there, which is good, but if there are too many parameters, The drawbacks of this approach can also be clearly exposed: the configuration parameter entries in appsetting can only be accessed by key names, cannot support complex hierarchical nodes, or strong types, and since they all use only one set, you will find that completely unrelated parameters are put together.

Want to get rid of this obsession? The custom configuration node will be a feasible way to solve this problem.

First, let's take a look at how to add a custom configuration node to the app.config or Web.config. In this blog, I'll look at 4 types of custom configuration nodes, with the final configuration file as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <configuration> <configSections> <section name= "M ySection111 "Type=" Rwconfigdemo.mysection1, Rwconfigdemo "/> <section name=" MySection222 "type=" Rwconfigdemo . 
        MySection2, Rwconfigdemo "/> <section name=" MySection333 "type=" Rwconfigdemo.mysection3, Rwconfigdemo "/>"

    <section name= "MySection444" type= "Rwconfigdemo.mysection4, Rwconfigdemo"/> </configSections> <mysection111 username= "Fish-li" url= "http://www.cnblogs.com/fish-li/" ></MySection111> <mysection2 22> <users username= "Fish" password= "Liqifeng" ></users> </MySection222> <mysectio
        n444> <add key= "AA" value= "11111" ></add> <add key= "BB" value= "22222" ></add> <add key= "CC" value= "33333" ></add> </MySection444> <MySection333> <comman D1> <![cdata[CREATE PROCEDURE changeproductquantity (@ProductID int, @q 
                uantity int) as update products set Quantity = @Quantity
            where ProductID = @ProductID; ]]> </Command1> <Command2> <!
                [cdata[CREATE PROCEDURE deletecategory (@CategoryID int)
            As delete from Categories where CategoryID = @CategoryID;
 ]]> </Command2> </MySection333> </configuration>

At the same time, I also provide all the sample code (at the end of the article to download), the demo program's interface is as follows:


Config file-property

First look at the simplest custom nodes, each of which is in the attribute mode:

<mysection111 username= "Fish-li" url= "http://www.cnblogs.com/fish-li/" ></MySection111>

The implementation code is as follows:

public class mysection1:configurationsection
{
    [ConfigurationProperty ("username", isrequired = True)]
    public string UserName
    {get
        {return this["UserName"]. ToString ();
        set {this["username"] = value;}
    }

    [ConfigurationProperty ("url", IsRequired = True)]
    public string Url
    {get
        {this["url"]. ToString ();
        set {this["url"] = value;}}
    }

Summary:
1. Customize a class to ConfigurationSection as a base class, with each attribute added [ConfigurationProperty], The name string passed in in the ConfigurationProperty constructor will be used in the config file to represent the property names of each parameter.
2. Read and write the value of the property to call this[], the base class to save, do not design field to save.
3. In order to be able to use the configuration node can be resolved, need to register in <configSections>: <sectionname= "MySection111" type= "Rwconfigdemo.mysection1, Rwconfigdemo "/>, and should pay attention to name=" MySection111 "and <mysection111 ... > is corresponding.

Description: The following will introduce another three configuration nodes, although a bit more complex, but some basic things and this node is the same, so I will not repeat the later.
Config file-Element

To look at a more complex point, each configuration item exists in the form of an XML element:

<MySection222>
    <users username= "Fish" password= "Liqifeng" ></users>
</mysection222 >

The implementation code is as follows:

public class mysection2:configurationsection
{
    [ConfigurationProperty ("users", IsRequired = True)]
    Public Mysectionelement users
        (mysectionelement) this["users";

}} public class Mysectionelement:configurationelement
{
    [ConfigurationProperty ("username", isrequired = True)] Public
    string UserName
    {Get
        {return this["username"]. ToString ();
        set {this["username"] = value;}
    }

    [ConfigurationProperty ("password", isrequired = True)]
    public string Password
    {get
        {return this["Password"]. ToString ();
        set {this["password"] = value;}}
    }

Summary:
1. Customize a class to ConfigurationSection as the base class, with each attribute in addition to adding [ConfigurationProperty]
2. The type is also custom, and the specific configuration properties are written in the ConfigurationElement inheritance class.
Config file-CDATA

Sometimes a configuration parameter contains longer text, such as a section of SQL script, or a section of HTML code, which requires a CDATA node. Suppose you want to implement a configuration that contains two of SQL scripts:

<MySection333>
    <Command1>
        <![ cdata[
            CREATE PROCEDURE changeproductquantity (
                @ProductID int,
                @Quantity int
            )
            as
            update Products Set Quantity = @Quantity 
            where ProductID = @ProductID;
        ]] >
    </Command1>
    <Command2>
        <![ cdata[
            CREATE PROCEDURE deletecategory (
                @CategoryID int
            )
            as
            delete from Categories
            where CategoryID = @CategoryID;
        ]] >
    </Command2>
</MySection333>

The implementation code is as follows:

public class Mysection3:configurationsection {[ConfigurationProperty (' Command1 ', isrequired = true)] public myt
    Extelement Command1 {get {return (mytextelement) this["Command1"];}  [ConfigurationProperty ("Command2", IsRequired = True)] public mytextelement Command2 {get} (mytextelement) this["Command2"]; }} public class Mytextelement:configurationelement {protected override void Deserializeelement (system.xml.x Mlreader 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;

 }
    }
}

Summary:
1. In the implementation of the general reference to MySection2,
2. Each configurationelement is controlled by us to read and write XML, which is to overload the method serializeelement,deserializeelement config file-Collection

<MySection444>
    <add key= "AA" value= "11111" ></add>
    <add key= "BB" value= "22222" >< /add>
    <add key= "cc" value= "33333" ></add>
</MySection444>

This similar configuration, in the ASP.net HttpHandler, HttpModule is too common to want to know how to implement them. The code is as follows:

Summary:
1. Create a derived class that inherits from ConfigurationElement for the parameter items in each collection, referring to the MySection1
2. Create a collection class that inherits from ConfigurationElementCollection for the collection, particularly when implementing a method that invokes the base class.
3. When you create an inherited class of configurationsection, you can create a property that represents the collection, and note the parameters of [ConfigurationProperty]. Config file-Read and write

I introduced the implementation classes of 4 custom configuration nodes one by one, and here's a look at how to read and write them.

Read configuration parameters:

mysection1 mySectioin1 = (MySection1) configurationmanager.getsection ("MySection111");
Txtusername1.text = Mysectioin1.username;


Txturl1.text = Mysectioin1.url;
MySection2 mySectioin2 = (MySection2) configurationmanager.getsection ("MySection222");
Txtusername2.text = MySectioin2.Users.UserName;


Txturl2.text = MySectioin2.Users.Password;
MySection3 MySection3 = (MySection3) configurationmanager.getsection ("MySection333");
Txtcommand1.text = MySection3.Command1.CommandText.Trim ();


Txtcommand2.text = MySection3.Command2.CommandText.Trim ();
MySection4 MySection4 = (MySection4) configurationmanager.getsection ("MySection444"); Txtkeyvalues.text = string.
                         Join ("\ r \ n", (from KV in mysection4.keyvalues.cast<mykeyvaluesetting> ()) Let S = String. Format ("{0}={1}", Kv.) Key, KV. Value) Select s).
ToArray ()); 

Summary: When reading a custom node, we need to invoke configurationmanager.getsection () to get the configuration node and transform it into our defined Configuration node class, which can then be accessed in a strongly typed manner.

Write configuration file:

configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none); MySection1 mySectioin1 = config.
GetSection ("MySection111") as MySection1;
Mysectioin1.username = TxtUsername1.Text.Trim ();

Mysectioin1.url = TxtUrl1.Text.Trim (); MySection2 mySection2 = config.
GetSection ("MySection222") as MySection2;
MySection2.Users.UserName = TxtUsername2.Text.Trim ();

MySection2.Users.Password = TxtUrl2.Text.Trim (); MySection3 mySection3 = config.
GetSection ("MySection333") as MySection3;
MySection3.Command1.CommandText = TxtCommand1.Text.Trim ();

MySection3.Command2.CommandText = TxtCommand2.Text.Trim (); MySection4 mySection4 = config.
GetSection ("MySection444") as MySection4;

MySection4.KeyValues.Clear (); (from S in txtkeyvalues.lines let P = s.indexof (' = ') where p > 0 select New mykeyvaluesetting {Key = S. Substring (0, p), Value = s.substring (P + 1)}). ToList ().

ForEach (kv => mySection4.KeyValues.Add (kv)); Config.
Save (); 

Summary: Before modifying the configuration node, we need to call Configurationmanager.openexeconfiguration (), and then call CONFIG. GetSection () After getting the node, turn to the type of node we defined, and then we can modify the parameters of our definition in a strongly typed way, and call Config at the end. Save ();

Attention:
1.. NET caches the data in order to optimize the read operation of the configuration node, and you need to call Configurationmanager.refreshsection ("...") if you want to use the modified results.
2. If you are modifying web.config, you need to use WebConfigurationManager
Read and write to already defined nodes in the. NET Framework

You've been demonstrating a custom node before, so how do you read the nodes already defined in the. NET Framework?

If I want to read the sender in the following configuration node.

<system.net>
    <mailSettings>
        <smtp from= "Fish.Q.Li@newegg.com" >
            <network/>
        </smtp>
    </mailSettings>
</system.net>

Read configuration parameters:

Smtpsection section = configurationmanager.getsection ("System.net/mailsettings/smtp") as Smtpsection;
Labmailfrom.text = "Mail from:" + section. from;

Write configuration file:

configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none); Smtpsection section = Config.
GetSection ("System.net/mailsettings/smtp") as smtpsection; Section.

from = "Fish.q.li@newegg.com2"; Config.

Save (); 

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.