Read and write configuration files

Source: Internet
Author: User

The System.configurationmanager class is used to read the configuration file. It has the following members:

First, AppSettings

AppSetting is the simplest configuration section, which is very simple to read and write.

Name Description
AppSettings Get Appsettingssection data for the current application default configuration
ConnectionStrings Get Connectionstringssection data for the current application default configuration

<?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 strappsettings =  system.configuration.configurationmanager.appsettings["DB"]; Gets the value            Console.WriteLine (strappsettings) through the property index;            String strconnection = system.configuration.configurationmanager.connectionstrings["ConnStr"]. ToString ();            Console.WriteLine (strconnection);            Console.readkey ();        }    }

  

For this one appsettings and connectionstrings are read by the two properties provided by ConfigurationManager. Usually most of the configuration information can be placed in the appsettings. But if you don't think it's enough, you can also use custom configuration information.

Ii. Custom Configuration section

  1, bring Handler

For custom configuration sections, configuration provides a number of handler classes that you can choose to use. Even if you don't feel enough, you can also customize the processing handler.
Learn how to use the three simple handler first:

    • System.Configuration.NameValueSectionHandler
    • System.Configuration.DictionarySectionHandler
    • System.Configuration.SingleTagSectionHandler

Example configuration file code:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "Person" type= "System.Configuration.NameValueSectionHandler"/> <!--returns the information    in the configuration section in the form of a Namevalue key value/Pair-- <section name= "man" type= "System.Configuration.DictionarySectionHandler"/>  <!-- Returns the information in the configuration section as a dictionary dictionary key-value pair--    <section name= "name" Type= " System.Configuration.SingleTagSectionHandler "/> <!--infrastructure. Handles each configuration section represented by a single XML tag in the. config file. -  </configSections>  <Person>    <add key= "Boss" Value= "Liu Bei"/>    <add key= "Dick" value= "Guan Yu"/>    <add key= "Old three" value= "Zhang Fei"/>  </Person>  <Man>    <add key= "Boss" Value= "Cao"/>    <add key= "Dick" value= "code wei"/>    <add key= "Old three" value= "Guo Jia"/>  </Man>    <name one= "1" two= "2" three= "3" four= "4" five= "5"/> <!--note that a single section of SingleTagSectionHandler is required for processing, But no matter how many of you can handle--></configuration>.

Read the code example:

static void Main (string[] args) {    //Read person name    NameValueCollection NVC = (NameValueCollection) Configurationmanager.getsection ("person");    foreach (String key in NVC. AllKeys)    {        Console.WriteLine (key + ":" + Nvc[key]);    }    Read Men    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 results are as follows:

  

  2. Custom Handler

Custom read nodes need to implement interface IConfigurationSectionHandler and provide a concrete 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 not start after version--      <section name= "person" type= " Consoleapplication1.personhandler,consoleapplication1,version=1.0.0.0,culture=neutral,publickeytoken=null " Allowlocation= "true" allowdefinition= "Everywhere"/>  </configSections>  <person age= "Name=" Liu Bei "/></configuration>

Main program code:

  Class Program {static void Main (string[] args) {Hashtable config = configurationmanager.ge            Tsection ("person") as Hashtable; Console.WriteLine ("Number of nodes is:" + CONFIG.)            Count); 2 key value pairs, where dekey can be converted again to a Hashtable foreach (DictionaryEntry dekey in config) {Con Sole.                WriteLine ("attribute element:" + deKey.Key.ToString ());                Hashtable attribs = (Hashtable) dekey.value; foreach (DictionaryEntry deattrib in Attribs) {Console.WriteLine (DeAttrib.Key.ToString (                ) + "=" + deAttrib.Value.ToString ());        }} console.readkey ();  }}//Note You must implement IConfigurationSectionHandler interface class Personhandler:iconfigurationsectionhandler {public Object Create (object parent, Object configcontext, System.Xml.XmlNode section) {Hashtable Myconfig = n            EW Hashtable ();            This section element, gets any properties. HashtablE myattribs = new Hashtable (); Iterates over the properties of the current node, foreach (XmlAttribute attrib in section. Attributes) {//If the current node is an attribute node, add the Myattribs if (Xmlnodetype.attribute = = attrib. NodeType) {Myattribs.add (attrib. Name, attrib.                Value); }}//Add the current attribute node collection into Myconfig myconfig.add (section.            Name, Myattribs);        return myconfig; }    }

The output results are as follows:

  

This kind of configuration code seems to be a little hard, after all, Hashtable level has two layers.

  3, property properties of the way read

    1. With this approach, 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 represent the property name of each parameter.
    2. Read and write the value of the property to call this[] or base[], save by the base class, do not design field to save.
    3. In order to be able to use configuration node can be resolved, need to register in <configSections>: <section name= "Person" type= "consoleapplication1.personsection, Consoleapplication1,version=1.0.0.0,culture=neutral,publickeytoken=null "allowlocation=" true "allowDefinition=" Everywhere "/>, and pay attention to name=" person "to be with <person .... > is corresponding.

Let's take a look at the configuration file:

<?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 not start after version--      <section name= "person" type= " Consoleapplication1.personsection,consoleapplication1,version=1.0.0.0,culture=neutral,publickeytoken=null " Allowlocation= "true" allowdefinition= "Everywhere"/>  </configSections>  <person age= "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 the System.Configuration.ConfigurationSection    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 results are as follows:

  

  4. Configure child elements

For a slightly more complex structure, the model class of the child element inherits from ConfigurationElement.

Config file code:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "complex" type= "Consoleapplication1.complexsection,consoleapplication1"/>  </configSections>  <complex height= "182" >    <child firstname= "Zhang" lastname= "Fly"/>  </complex></configuration >

Main program code:

  Class Program {static void Main (string[] args) {complexsection sec = ConfigurationManager.            GetSection ("complex") as complexsection; Console.WriteLine (sec.          Height); Access Property Console.WriteLine (sec. Child.firstname); Access child Node Properties Console.WriteLine (Sec.  Child.lastname);        Access child node Properties Console.readkey (); }} public class Complexsection:configurationsection {[ConfigurationProperty ("height", isrequired = Tru            e)] 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 = tr      UE, IsKey = True)]  public string FirstName {get {return (string) base["FirstName"];}        set {base["firstName"] = value;} } [ConfigurationProperty ("LastName", IsRequired = True)] public string LastName {get {RE Turn (String) base["LastName"];        } set {base["lastName"] = value;} }    }

Output Result:

  

  5. CDATA In the configuration file

Sometimes, in a configuration file, there might be some more complex pieces of code that would use the CDATA XML.

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "MySection" type= "consoleapplication1.mysection, ConsoleApplication1"/>  </configSections>  < mysection>    <HTML>      <![ cdata[          <div style= "# font-size:24px" > Bold display </div>      ]]>    </HTML>    <SQL>      <! [cdata[          SELECT TOP ten * from person      ]]>    </SQL>  </mysection></configuration >

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.ConfigurationSec            tion {[ConfigurationProperty ("html", IsRequired = False)] public mytextelement HTML {            get {return (mytextelement) base["HTML"];}        set {base["HTML"] = value;} } [ConfigurationProperty ("sql", IsRequired = False)] public mytextelement SQL {get {Retu RN (mytextelement) base["SQL";        } set {base["SQL"] = value;} }} public class Mytextelement:configurationelement {protected override void Deserializeelement (System. Xml.xmlreader 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 {RE Turn this["Data"]. ToString ();        } set {this["data"] = value;} }    }}

The output is as follows:

  

  6. Configuration element Collection

Similar to the following configuration, in the HttpHandler of ASP. HttpModule, it is too common.

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "MySection" type= "consoleapplication1.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//All configuration nodes should select this base class {private static readonly Configura Tionproperty s_property = new ConfigurationProperty (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:configurati OnelEmentcollection//Customize a collection {//Basically, all of the methods simply call the implementation of the base class. Public mykeyvaluecollection (): Base (stringcomparer.ordinalignorecase)//Ignore Case {}//actually the key is this indexer 。        But it is also called the implementation of the base class, just do the next type of turn on the line. New public mykeyvaluesetting this[string name] {get {return (mykeyvaluesetting) base. Baseget (name);        }}//The following two methods must be implemented in an abstract class.        protected override ConfigurationElement Createnewelement () {return new mykeyvaluesetting (); } protected Override Object Getelementkey (configurationelement Element) {return (Mykeyvaluesett ing) element.        Key;            }//Description: If you do not need to modify the collection in code, you can not implement 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:configurationelement//Each element in the collection {[ConfigurationProperty ("key", IsRequired = t Rue)] public string Key {get {return this["key"]. ToString ();        } set {this["key"] = value;} } [ConfigurationProperty ("value", IsRequired = True)] public string value {get {return T his["Value"]. ToString ();        } set {this["value"] = value;} }    }

The output is as follows:

  

Summary:

1. Create a derived class that inherits from ConfigurationElement for the parameter items in each collection.
2. Create a collection class that inherits from ConfigurationElementCollection for the collection, when implemented primarily as a method of calling the base class.
3. When creating an inherited class of configurationsection, it is possible to create a property that represents the collection, noting the parameters of [ConfigurationProperty].

  7. Write the Configuration node

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 = "Shake Sacred cow";    Section.age = 10000;    Config. Save ();    Configurationmanager.refreshsection ("person");  Make the modified result effective

Before modifying the configuration node, we need to call Configurationmanager.openexeconfiguration () and then call CONFIG. GetSection () After the node is obtained, it goes to the type of node we define, then we can modify each parameter item we define in a strongly typed way, and finally call CONFIG. Save ();

Attention:

    1. . NET caches the data in order to optimize the read operation of the configuration node, and if you want to use the modified results, you also need to call Configurationmanager.refreshsection ("...").
    2. If you are modifying Web. config, you need to use WebConfigurationManager.

  8. Read nodes already defined in the. Net Framework

The read of the. Net framework defined nodes is simple:

  <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 configuration in the Mechine on the server will be read together.

In Web. config is read-only, not written, and not the same as the above example, not repeated here.

Read and write configuration files

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.