c# ConfigurationSection

怎么把自己的配置文件配置到app.config中?

  • 方案1:在app.config中添加
 <!--应用配置-->
  <appSettings configSource="Conf\AppSettings.config" />

如果我需要自己定义单独的多个配置文件,又该怎么处理才可以把配置文件添加app.config中呢?

  • 方案2:定义ConfigurationSection类
MyConfigurationSection  
 1 public class MyConfigurationSection : ConfigurationSection
 2 {
 3     [ConfigurationProperty("", IsDefaultCollection = true)]
 4     public KeyValueConfigurationElementCollection My
 5     {
 6         get { return (KeyValueConfigurationElementCollection)base[""]; }
 7     }
 8 
 9     public string GetValueByKey(string key)
10     {
11         foreach (KeyValueConfigurationElement item in this.My)
12         {
13             if (item.Key == key)
14                 return item.Value;
15         }
16 
17         return string.Empty;
18     }
19 
20     //[ConfigurationProperty("configSource", IsRequired = false)]
21     //public string ConfigSource
22     //{
23     //    get { return (string)base["configSource"]; }
24     //    set
25     //    {
26     //        base["configSource"] = value;
27     //    }
28     //}
29 }

KeyValueConfigurationElementCollection

 1 public class KeyValueConfigurationElementCollection : ConfigurationElementCollection
 2 {
 3     protected override ConfigurationElement CreateNewElement()
 4     {
 5         return new KeyValueConfigurationElement();
 6     }
 7 
 8     protected override object GetElementKey(ConfigurationElement element)
 9     {
10         return (element as KeyValueConfigurationElement).Key;
11     }
12 
13     public override ConfigurationElementCollectionType CollectionType
14     {
15         get { return ConfigurationElementCollectionType.BasicMap; }
16     }
17 
18     protected override string ElementName
19     {
20         get { return "add"; }
21     }
22 }

KeyValueConfigurationElement

 1 public class KeyValueConfigurationElement : ConfigurationElement
 2 {
 3     [ConfigurationProperty("key", IsRequired = true)]
 4     public string Key
 5     {
 6         get { return (string)base["key"]; }
 7         set { base["key"] = value; }
 8     }
 9 
10     [ConfigurationProperty("value", IsRequired = true)]
11     public string Value
12     {
13         get { return (string)base["value"]; }
14         set { base["value"] = value; }
15     }
16 }

修改app.config配置文件:

<configSections>
    <section name="my" type="DTCore.MyConfigurationSection,DTCore"/>
</configSections>

<mre configSource="Conf\My_Settings.config" />
Conf\My_Settings.config

1 <?xml version="1.0" encoding="utf-8"?>
2 <my>
3   <add key="DT.AKey" value="c key"/>
4   <add key="DT.CKey.RIPPRB" value="the value"/>
5 </my>

怎么调用:

1 MyConfigurationSection mySection=(MyConfigurationSection)ConfigurationManager.GetSection("my");
2 string value=mySection.GetValueByKey("DT.AKey");

 

posted @ 2015-11-24 19:22  cctext  阅读(1873)  评论(0编辑  收藏  举报