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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With