Kevin Kevin - 3 months ago 8
C# Question

Write a section in app.config file

I've looked here about making changes to the app.config file using ConfigurationManager. This seems to write values under

<appSettings>
in the file.

I feel my question might be a very similar change, but I can't quite work out how to do it.

I've defined a
configSections
element in my app.config file, for example
<section name="Example".../>
, and in the config file it's been given some value:

<Example file="C:\temp\".../>
.

If I use the command
ConfigurationManager.GetSection("Example")
, I can get this value.

I wondered, is there a way to change this value at runtime? So I'd like to use
ConfigurationManager.GetSection("Example")
at a later point, and have the new (changed) value returned - if this is possible? Thank you,

Answer

Putting that information in the config-file is only one step to achieve what you're looking for.

Your <Example>-node is a custom section, that's unknown at that time. For enabling the ConfigurationManager to parse your section to an actual object at runtime, you'll have to define your section as a class deriving from ConfigurationSection:

public class ExampleSection : ConfigurationSection
{
    [ConfigurationProperty("file", IsRequired = true)]
    public string File
    {
        get
        { 
            return this["file"]; 
        }
        set
        { 
            this["file"] = value; 
        }
    }

For a complete example, please have a look at this comprehensive MSDN-article.