将web.config部分读取到List

我在web.config中有这个:

      

我想读取所有部分“MySection”并获取List所有值(例如:“10”,“20”,“30”)

谢谢,

首先,我建议使用Unity Configuration 。

码:

 public class MySection : ConfigurationSection { protected static ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); private static ConfigurationProperty propElements = new ConfigurationProperty("elements", typeof(MyElementCollection), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsDefaultCollection); static BotSection() { properties.Add(propElements); } [ConfigurationProperty("elements", DefaultValue = null, IsRequired = true)] [ConfigurationCollection(typeof(MyElementCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")] public MyElementCollection Elements { get { return (MyElementCollection)this[propElements]; } set { this[propElements] = value; } } } public class MyElementCollection : ConfigurationElementCollection, IEnumerable // most important difference with default solution { public void Add(MyElement element) { base.BaseAdd(element); } public void Clear() { base.BaseClear(); } protected override ConfigurationElement CreateNewElement() { return new MyElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((MyElement)element).Id; } IEnumerator IEnumerable.GetEnumerator() { return this.OfType().GetEnumerator(); } } public class MyElement : ConfigurationElement { protected static ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); private static ConfigurationProperty propValue= new ConfigurationProperty("value", typeof(int), -1, ConfigurationPropertyOptions.IsRequired); public int Value { get { return (int)this[propValue]; } set { this[propValue] = value; } } } 

配置:

   

我建议你看一下CodePlex上优秀的开源Configuration Section Designer项目。 它允许您使用Visual Studio中托管的设计器创建自定义配置节。

例如,自定义配置部分设计如下:

简单自定义部分 将导致如下配置文件:

    

可以像这样以编程方式使用:

 foreach (MySetting setting in MySection.Instance.Items) { Console.WriteLine("{0}: {1}", setting.Name, setting.Value); }