通过自定义App.config设置检索/循环

时间:2014-12-26 15:59:20

标签: c# configuration app-config

我正在尝试从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)中的项目并将它们发送到查询进行处理。

1 个答案:

答案 0 :(得分:2)

你走了:

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