【问题标题】:How can I retrieve list of custom configuration sections in the .config file using C#? [duplicate]如何使用 C# 在 .config 文件中检索自定义配置部分的列表? [复制]
【发布时间】:2013-02-21 16:04:54
【问题描述】:
当我尝试使用
检索 .config 文件中的部分列表时
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections 集合包含一堆系统部分,但我在 configSections 标记中定义的文件中没有一个部分。
【问题讨论】:
标签:
c#
configurationmanager
configsection
【解决方案1】:
这是一个blog article,应该可以满足您的需求。但是为了确保答案仍然可用,我也将把代码放在这里。简而言之,请确保您引用了 System.Configuration 程序集,然后利用 ConfigurationManager 类获取您想要的非常具体的部分。
using System;
using System.Configuration;
public class BlogSettings : ConfigurationSection
{
private static BlogSettings settings
= ConfigurationManager.GetSection("BlogSettings") as BlogSettings;
public static BlogSettings Settings
{
get
{
return settings;
}
}
[ConfigurationProperty("frontPagePostCount"
, DefaultValue = 20
, IsRequired = false)]
[IntegerValidator(MinValue = 1
, MaxValue = 100)]
public int FrontPagePostCount
{
get { return (int)this["frontPagePostCount"]; }
set { this["frontPagePostCount"] = value; }
}
[ConfigurationProperty("title"
, IsRequired=true)]
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\"
, MinLength=1
, MaxLength=256)]
public string Title
{
get { return (string)this["title"]; }
set { this["title"] = value; }
}
}
确保您阅读了博客文章 - 它将为您提供背景知识,以便您可以将其融入您的解决方案。