1

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,

Community
  • 1
  • 1
Kevin C
  • 324
  • 1
  • 14

2 Answers2

4

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.

Jan Köhler
  • 5,817
  • 5
  • 26
  • 35
  • Thank you for this! Yes I've checked and I have an `ExampleSection` with `set`. If I cast the result of `GetSection` as `ExampleSection`, make the change, and use `config.Save`, will the edit I made locally be saved to the config file? – Kevin C Aug 26 '16 at 13:38
  • Not being able to try it myself right now, I'd _guess_ that should work. Just give it a try ☺ – Jan Köhler Aug 26 '16 at 13:58
3

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

update appsettings and custom configuration sections in appconfig at runtime

Aida Bigonah
  • 197
  • 10