如何使用C#检索.config文件中的自定义配置节列表?

当我尝试使用时检索.config文件中的部分列表

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

config.Sections集合包含一堆系统部分,但我没有在configSections标记中定义文件的部分。

这是一篇博客文章 ,可以为您提供所需内容。 但为了确保答案保持可用,我将在这里删除代码。 简而言之,确保引用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; } } } 

请务必阅读博客文章 – 它将为您提供背景信息,以便您可以将其融入您的解决方案中。