Basic skills (16) -------- read the custom tag value of App. config, -------- app. config

Source: Internet
Author: User

Basic skills (16) -------- read the custom tag value of App. config, -------- app. config
I. Program

 

II. Specific Code

Config Configuration:

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <section name = "MySection111" type = "configToRead. mySection1, configToRead "/> <section name =" MySection444 "type =" configToRead. mySection4, configToRead "/> </configSections> <MySection111 username =" "url =" http://www.cnblogs.com/hongmaju/ "> </MySection111> <MySection444> <add key =" aa "value =" 11111 "> </add> <add key =" bb "value =" 22222 "> </add> <add key =" cc "value =" 33333 "> </add> </MySection444> </configuration>

 

To use custom configuration in a program, we also need to implement the type of access to this configuration block. Generally, we need to do the following three things:
1. The definition type is inherited from System. Configuration. ConfigurationSection.
2. Define the attributes of the configuration class. These attributes need to be modified using the ConfigurationProperty feature, and specify the names and other restrictions of the attributes in the configuration section.
3. get, set

MySection1.cs code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;namespace configToRead{    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 { return this["url"].ToString(); }            set { this["url"] = value; }        }    }}

MySection4.cs code
Using System; using System. collections. generic; using System. linq; using System. text; using System. configuration; namespace configToRead {public class MySection4: ConfigurationSection // all Configuration nodes must select this base class {private static readonly ConfigurationProperty s_property = new ConfigurationProperty (string. empty, typeof (MyKeyValueCollection), null, ConfigurationPropertyOptions. isDefaultCollection); [ConfigurationP Roperty ("", Options = ConfigurationPropertyOptions. isDefaultCollection)] public MyKeyValueCollection KeyValues {get {return (MyKeyValueCollection) base [s_property] ;}} [ConfigurationCollection (typeof (MyKeyValueSetting)] public class MyKeyValueCollection: configurationElementCollection // customize a set {// basically, all methods 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 ;}}}}

 

Front-end code:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using configToRead;using System.Configuration;using System.Net.Configuration;using System.Collections.Specialized;namespace configToRead{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111");            textBox1.Text = mySectioin1.UserName;            textBox1.Text += mySectioin1.Url;            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());                   }        private void Form1_Load(object sender, EventArgs e)        {            MySection4 mySection4 = (MySection4)ConfigurationManager.GetSection("MySection444");                comboBox1.Items.AddRange((from kv in mySection4.KeyValues.Cast<MyKeyValueSetting>()                                     let s = string.Format("{0}", kv.Key)                                     select s).ToArray());//linqToSql        }    }}

 

Iii. troubleshooting

Include App. config in the project.


C # appconfig traverse and read custom nodes

You have a problem with the xml design. Recommended design:
<Serial id = "1"> <add key = "PortName" value = "COM7"/> <add key = "BaudRate" value = "9600"/> <add key = "DataBits" value = "8"/> <add key = "Device" value = "AD_1000"/> <add key = "IsOpne" value = "YES"/> </ serial> <Serial id = "2"> <add key = "PortName" value = "COM7"/> <add key = "BaudRate" value = "9600"/> <add key = "DataBits" value = "8"/> <add key = "Device" value = "AD_1000"/> <add key = "IsOpne" value = "YES"/> </Serial> easy to process


Use winform c # to read data from appconfig, and then read the values set in one of the Child Nodes and write detailed code.

Nodes in the configuration file:
<Deleetask>
<Add key = "test" value = "testValue"/>
</AppSettings>
Code:
String _ value = System. Configuration. ConfigurationManager. receivettings ["test"]. ToString ();

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.