保存集合属性到App.config

怎样在App.config文件中,自定义节点保存如下格式的内容:
 1<?xml version="1.0" encoding="utf-8" ?>
 2    <configuration>
 3        <configSections>
 4            <section name="TestSection" type="Test.TestSection,TestService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
 5  </configSections>
 6        <TestSection name="test" password="******">
 7   <channels>
 8    <add id="one" name="channel_1" />
 9    <add id="two" name="channel_2" />
10    <add id="three" name="channel_3" />
11   </channels>
12  </TestSection>
13</configuration>

1、元素要继承ConfigurationElement
 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Configuration;
 5using System.Xml;
 6namespace Test
 7{
 8    /// <summary>
 9    /// 通道
10    /// </summary>

11    public class Channel : ConfigurationElement
12    {
13
14        public Channel() 
15        {
16
17        }

18        public Channel(string name) : this(Guid.NewGuid().ToString(),name)
19        {
20        }

21        public Channel(string id ,string name)
22        {
23            ID = id;
24            Name = name;
25        }

26
27        /// <summary>
28        /// 通道编号
29        /// </summary>

30        [ConfigurationProperty("id",IsRequired=true)]
31        public string ID
32        {
33            get return (stringthis["id"]; }
34            set this["id"= value; }
35        }

36
37        /// <summary>
38        /// 通道名称
39        /// </summary>

40        [ConfigurationProperty("name",IsRequired=true)]
41        public string Name
42        {
43            get return (stringthis["name"]; }
44            set this["name"= value; }
45        }

46
47        protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
48        {
49            base.DeserializeElement(reader, serializeCollectionKey);
50        }

51        protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
52        {
53            return  base.SerializeElement(writer, serializeCollectionKey);
54        }

55
56        protected override bool IsModified()
57        {
58           return   base.IsModified();
59        }

60    }

61}

62
2、集合要继承ConfigurationElementCollection
  1using System;
  2using System.Collections.Generic;
  3using System.Text;
  4using System.Configuration;
  5namespace Test
  6{
  7         public class ChannelCollection : ConfigurationElementCollection
  8        {
  9            public ChannelCollection()
 10            {
 11                Channel channel = (Channel)CreateNewElement();
 12                Add(channel);
 13            }

 14
 15            public override ConfigurationElementCollectionType CollectionType
 16            {
 17                get
 18                {
 19                    return ConfigurationElementCollectionType.AddRemoveClearMap;
 20                }

 21            }

 22
 23            protected override ConfigurationElement CreateNewElement()
 24            {
 25                return new Channel();
 26            }

 27
 28
 29            protected override ConfigurationElement CreateNewElement(string elementName)
 30            {
 31                return new Channel(elementName);
 32            }

 33
 34
 35            protected override Object GetElementKey(ConfigurationElement element)
 36            {
 37                return ((Channel)element).Name;
 38            }

 39
 40
 41            public new string AddElementName
 42            {
 43                get
 44                return base.AddElementName; }
 45
 46                set
 47                base.AddElementName = value; }
 48
 49            }

 50
 51            public new string ClearElementName
 52            {
 53                get
 54                return base.ClearElementName; }
 55
 56                set
 57                base.AddElementName = value; }
 58
 59            }

 60
 61            public new string RemoveElementName
 62            {
 63                get
 64                return base.RemoveElementName; }
 65
 66
 67            }

 68
 69            public new int Count
 70            {
 71
 72                get return base.Count; }
 73
 74            }

 75
 76
 77            public Channel this[int index]
 78            {
 79                get
 80                {
 81                    return (Channel)BaseGet(index);
 82                }

 83                set
 84                {
 85                    if (BaseGet(index) != null)
 86                    {
 87                        BaseRemoveAt(index);
 88                    }

 89                    BaseAdd(index, value);
 90                }

 91            }

 92
 93            new public Channel this[string Name]
 94            {
 95                get
 96                {
 97                    return (Channel)BaseGet(Name);
 98                }

 99            }

100
101            public int IndexOf(Channel channel)
102            {
103                return BaseIndexOf(channel);
104            }

105
106            public void Add(Channel channel)
107            {
108                BaseAdd(channel);
109
110                // Add custom code here.
111            }

112
113            protected override void
114                BaseAdd(ConfigurationElement element)
115            {
116                BaseAdd(element, false);
117                // Add custom code here.
118            }

119
120            public void Remove(Channel channel)
121            {
122                if (BaseIndexOf(channel) >= 0)
123                    BaseRemove(channel.Name);
124            }

125
126            public void RemoveAt(int index)
127            {
128                BaseRemoveAt(index);
129            }

130
131            public void Remove(string name)
132            {
133                BaseRemove(name);
134            }

135
136            public void Clear()
137            {
138                BaseClear();
139                // Add custom code here.
140            }

141        }

142}
3、节点要继承ConfigurationSection
 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Configuration;
 5using System.Xml;
 6
 7namespace Test
 8{
 9    /// <summary>
10    /// Test配置信息
11    /// </summary>

12    public class TestSection : ConfigurationSection 
13    {
14        /// <summary>
15        /// Test名称
16        /// </summary>

17        [ConfigurationProperty("name",IsRequired=true)]
18        public string Name
19        {
20            get return (stringthis["name"]; }
21            set this["name"= value; }
22        }

23        
24        /// <summary>
25        /// Test通道集合
26        /// </summary>

27        [ConfigurationProperty("channels",IsDefaultCollection = false)]
28        public ChannelCollection Channels
29        {
30            get 
31            {
32                ChannelCollection channels = (ChannelCollection)base["channels"];
33                return channels; 
34            
35            }

36   
37        }

38
39        /// <summary>
40        /// 密码
41        /// </summary>

42        [ConfigurationProperty("password",IsRequired= true)]
43        public string Password
44        {
45            get return (stringthis["password"]; }
46            set this["password"= value; }
47        }

48
49         protected override void DeserializeSection(XmlReader reader)
50        {
51            base.DeserializeSection(reader);
52        }

53
54        protected override string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode)
55        {
56            string s = base.SerializeSection(parentElement, name, saveMode);
57            return s;
58        }

59    }

60}

61
4、Demo
 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel;
 4using System.Data;
 5using System.Drawing;
 6using System.Text;
 7using System.Windows.Forms;
 8using System.Configuration;
 9
10namespace Test
11{
12    public partial class Demo : Form
13    {
14        public Demo()
15        {
16            InitializeComponent();
17        }

18
19        private void button1_Click(object sender, EventArgs e)
20        {
21            SaveConfig();
22        }

23        public void SaveConfig()
24        {
25            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
26
27            Channel[] channel = {      new Channel("one","channel_Red"),
28                                        new Channel("two","channel_Blue"),
29                                        new Channel("three","channel_Green")
30                                 }
;
31
32            config.Sections.Remove("ClientSection");
33
34            ClientSection section = new ClientSection();
35            section.Name = "服务器1";
36            section.Password = "123456";
37            for (int i = 0; i < channel.Length; i++)
38            {
39                section.Channels.Add(channel[i]);
40            }

41            config.Sections.Add("ClientSection", section);
42            config.Save();
43        }

44    }

45}
原文地址:https://www.cnblogs.com/xiaowy/p/477237.html