在.net项目中, 可能有时候会遇到需要自定义配置节点,下面是自己在项目中用到的一个
1.配置定制类
-----全局配置
public class SubscribeTypeConfig : ConfigurationSection
{[ConfigurationProperty("Name", DefaultValue = "SubscribeType", IsRequired = true, IsKey = false)]
public String Name
{
get
{
return (string)this["Name"];
}
set
{
this["Name"] = value;
}
}
[ConfigurationProperty("SubscribeTypeConfigs", IsDefaultCollection = false)]
public SubscribeTypeConfigCollection SubscribeTypeConfigs
{
get
{
return (SubscribeTypeConfigCollection)this["SubscribeTypeConfigs"];
}
}
}
---定义集合
public class SubscribeTypeConfigCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new SubscribeTypeConfigElement();
}
protected override Object GetElementKey(ConfigurationElement element)
{
return ((SubscribeTypeConfigElement)element).Name;
}
}
---定义集合中的元素
public class SubscribeTypeConfigElement : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "mail", IsRequired = true, IsKey = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
}
2.下面是在web.config中需要配置的
---configSections中的配置
<section name="SendService" type="Songjiang.Platform.Subscribe.Common.SendServiceConfig,Songjiang.Platform.Subscribe.Common"/>
----具体配置节点
<SendService Name="SendService">
<SendServiceConfigs>
<add name="MailSend" ></add>
</SendServiceConfigs>
</SendService>
3.读取配置
SendServiceConfig ssc = (SendServiceConfig)ConfigurationManager.GetSection("SendService");
foreach (ServiceConfigElement sce in ssc.SendServiceConfigs)
{
if (sce.SendTime == DateTime.Now.ToString("hh:mm"))
{
//etc..
}
}
ps:这只是最简单的配置形式,还有其他的配置方式。写在这里 ,便于记忆。