How can I retrieve list of custom configuration sections in the .config file using C#? [duplicate]

浪子不回头ぞ 提交于 2019-12-23 08:39:23

问题


When I try to retrieve the list of sections in the .config file using

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

the config.Sections collection contains a bunch of system section but none of the sections I have file defined in the configSections tag.


回答1:


Here is a blog article that should get you what you want. But to ensure that the answer stays available I'm going to drop the code in place here too. In short, make sure you're referencing the System.Configuration assembly and then leverage the ConfigurationManager class to get at the very specific sections you want.

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; }
  }
}

Make sure you read the blog article - it will give you the background so that you can fit it into your solution.



来源:https://stackoverflow.com/questions/15254566/how-can-i-retrieve-list-of-custom-configuration-sections-in-the-config-file-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!