Kevin C
Kevin C

Reputation: 344

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,

Upvotes: 1

Views: 2577

Answers (2)

Jan K&#246;hler
Jan K&#246;hler

Reputation: 6030

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.

Upvotes: 4

Aida Bigonah
Aida Bigonah

Reputation: 197

You can check this link , it's a good example for your issue :

update appsettings and custom configuration sections in appconfig at runtime

Upvotes: 3

Related Questions