我想从我的app.config文件采取的自定义配置节和值传递给查询更新等。
这里是我的CustomConfig汇编代码
using System;
using System.Configuration;
namespace CustomConfig
{
public class Element : ConfigurationElement
{
private const string LevelKey = "level";
private const string DaysAgedValue = "daysaged";
[ConfigurationProperty(LevelKey, IsRequired = true, IsKey = true)]
public string Level
{
get { return (string)this[LevelKey]; }
set { this[LevelKey] = value; }
}
[ConfigurationProperty(DaysAgedValue, IsRequired = true, IsKey = false)]
public string DaysAged
{
get { return (string)this[DaysAgedValue]; }
set { this[DaysAgedValue] = value; }
}
}
public class ElementCollection : ConfigurationElementCollection
{
public ElementCollection()
{
this.AddElementName = "Settings";
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as Element).Level;
}
protected override ConfigurationElement CreateNewElement()
{
return new Element();
}
public new Element this[string key]
{
get { return base.BaseGet(key) as Element; }
}
public Element this[int ind]
{
get { return base.BaseGet(ind) as Element; }
}
}
public class Section : ConfigurationSection
{
public const string sectionName = "PrintLogPurgeSettings";
[ConfigurationProperty("", IsDefaultCollection = true)]
public ElementCollection PrintLogPurgeSettings
{
get
{
return this[""] as ElementCollection;
}
}
public static Section GetSection()
{
return (Section)ConfigurationManager.GetSection(sectionName);
}
}
}
这里是我的app.config文件
<?xml version="1.0"?>
<configuration>
<configSections>
<!--<section name="PrintLogPurgeSettings" type="CustomConfig.PrintLogPurgeConfigSection, PrintingServiceLogPurge" />-->
<section name="PrintLogPurgeSettings" type="CustomConfig.Section, PrintingServiceLogPurge" />
</configSections>
<!---Print Log Level and Age Settings-->
<PrintLogPurgeSettings>
<Settings level="1" daysaged="30"/>
<Settings level="2" daysaged="60"/>
<Settings level="3" daysaged="60"/>
<Settings level="4" daysaged="90"/>
<Settings level="5" daysaged="90"/>
<Settings level="6" daysaged="180"/>
</PrintLogPurgeSettings>
我想通过项目环在PrintLogPurgeSettings(1-6),并将它们发送到查询处理。
干得好:
CustomConfig.Section c = ConfigurationManager.GetSection("PrintLogPurgeSettings") as CustomConfig.Section;
foreach (CustomConfig.Element element in c.PrintLogPurgeSettings.Cast<CustomConfig.Element>())
{
Console.WriteLine("{0}:{1}", element.Level, element.DaysAged);
}
它打印:
1:30
2:60
3:60
4:90
5:90
6:180