阅读web.config部分,列出 [英] Read web.config section to List
本文介绍了阅读web.config部分,列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个在web.config中:
I have this in a web.config :
<MySection>
<Setting1 Value="10" />
<Setting2 Value="20" />
<Setting3 Value="30" />
<Setting4 Value="40" />
</MySection>
我想读的所有部分MySection,并获得所有的值设置为名单,其中,串&GT;
(例如:10,20,30 )
I'd like read the all section "MySection" and get all value to a List<string>
(ex : "10","20","30")
谢谢
推荐答案
首先,我建议用使用<一个href="http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration%28PandP.50%29.aspx"相对=nofollow>统一配置。
code:
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<ConfigurationElement> // 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<MyElement> IEnumerable<MyElement>.GetEnumerator()
{
return this.OfType<MyElement>().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;
}
}
}
配置:
<configuration>
<configSections>
<section name="MySection" type="MySection, MyAssembly"/>
</configSections>
<MySection>
<elements>
<clear />
<add value="10" />
<remove value="10" />
<add value="20" />
<add value="30" />
</elements>
</MySection>
</configuration>
这篇关于阅读web.config部分,列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文