Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 453
Roussi Ivanov Avatar asked Mar 06 '13 17:03

Roussi Ivanov


People also ask

What is a Config file in c#?

Config File? A configuration file (web. config) is used to manage various settings that define a website. The settings are stored in XML files that are separate from your application code. In this way you can configure settings independently from your code.

How do I add a config section in app config?

Open the App. config file and add the configSections, sectionGroup and section to it. We need to specify the name and fully qualified type of all the section and section group.


1 Answers

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.

like image 128
Mike Perrenoud Avatar answered Sep 20 '22 10:09

Mike Perrenoud