0

My XML file looks like:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="databaseTypes" type="System.Configuration.NameValueSectionHandler" />
    <section name="dataDictionary" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <databaseTypes>
    <add key="ExampleServerPrefix_T" value="Connection_String_For_ExampleServer" />
    <add key="ExampleServer2Prefix_T" value="Connection_String_For_ExampleServer_2" />
    <add key="COPYLIVE_" value="ODBC;DSN=s2;" />
  </databaseTypes>
  <dataDictionary>
    <!-- Other pairs in this section -->
  </dataDictionary>
</configuration>

What I am trying to achieve is to be able to add and remove key-value pairs from the databaseTypes section. So for example to would like to dynamically add a run time a new pair <add key="blah" value="ODBC;blah" />.

First its useful to know is this possible? If so how because I can't find any relevant documentation or examples on how this is done.

Ben
  • 2,518
  • 4
  • 18
  • 31
  • It is definitely possibly, I do it by implementing IConfigurationSectionHandler. Do you already have a databaseType class defined? – Kevin Dec 11 '14 at 19:54
  • No I dont have one defined. Do I need one? I am only using it as a dictionary. – Ben Dec 11 '14 at 19:56
  • You don't have to it is just one way of doing it. Here is an article that may help: http://stackoverflow.com/questions/2502091/writing-custom-sections-into-app-config – Kevin Dec 11 '14 at 20:03
  • Here is another very good article: http://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/ – Kevin Dec 11 '14 at 20:04
  • @Kevin very good article, thank you. This article has partially solved my problem. I have it implemented and it is "saving" the new key-value pairs excepting it is really saving it. The new key-value pairs are saved in memory untill the program has finished executing it is never actually written to the XML file. Any ideas? – Ben Dec 15 '14 at 10:25
  • @Kevin apologies, it is working perfectly. That article helped solve my problem. Add it as an answer if you want rep – Ben Dec 15 '14 at 11:45
  • glad you got it all figured out! – Kevin Dec 15 '14 at 12:16

1 Answers1

1

Ben,

Here are two articles that will help you with adding key/value pairs to the config:

Writing custom sections to app.config

Writing custom sections into app.config

Update AppSettings and custom configuration sections in App.config at runtime

http://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/

Community
  • 1
  • 1
Kevin
  • 2,566
  • 1
  • 11
  • 12