How can I get a list of custom configuration sections in a .config file using C #?

When I try to get a list of sections in a .config file using

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

The config.Sections collection contains a bunch of system partitions, but none of the partitions that have a file are defined in the configSections tag.

+6
source share
1 answer

Here is a blog article that should get what you want. But to ensure that the answer remains available, I am also going to delete the code. In short, make sure you reference the System.Configuration assembly, and then use the ConfigurationManager class to get the sections you need.

 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 - this will give you the background so you can put it in your solution.

+2
source

All Articles