-->

How can I retrieve list of custom configuration se

2019-06-20 05:17发布

问题:

This question already has an answer here:

  • Custom Configuration for app.config - collections of sections? 2 answers

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.