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

如何使用C#检索.config文件中的自定义配置节列表?,c#,configurationmanager,configsection,C#,Configurationmanager,Configsection,当我尝试使用检索.config文件中的节列表时 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.Sections集合包含一组系统节,但我在configSections标记中定义的文件中没有一个节。下面是一个可以满足您需要的部分。但是为了确保答案仍然有效,我也将把代码放在这里。简而言之,请确保您引用的是System.Configuration

当我尝试使用检索.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; }
  }
}
确保你读了这篇博客文章——它会给你背景信息,这样你就可以把它融入你的解决方案中