Question app.config data - ConfigurationManager.AppSettings - How to modify and save?

Samael117

New member
Joined
Jun 23, 2020
Messages
1
Programming Experience
3-5
(this is my first post here,every critic on the form is welcome)
my problem is the following, my program has a app.setting with config section that is needed for an extern .dll I'm using. It's working fine but I want to be able to write the section and data in them at runtime, but i can't find a way to do it.

My app.config look like that :
XML:
<configuration>
    <configSections>
        <section name="DirectoryServerConfiguration" type="System.Configuration.NameValueSectionHandler"/>
    </configSections>
    <!--<DirectoryServerConfiguration configSource="SubConfigFiles\YPAdress.config"/>-->
</configuration>
(I commented the file with the definition because I want to do it in my code)

and the data I want to add in DirectoryServerConfiguration with is :
XML:
<DirectoryServerConfiguration>
    <add key="YPSAddress" value="my https IP" />
</DirectoryServerConfiguration>
I tried many things, from trying to add key/value from a GetSection (before realising it's read only). To creating a custom class deriving from ConfigurationSection.
C#:
public class DirectoryServerConfiguration : ConfigurationSection
{
  public DirectoryServerConfiguration()
  {
  }

  [ConfigurationProperty("Key")]
  public string Key
  {
    get { return (string)this["Key"]; }
    set { this["Key"] = value; }
  }

  [ConfigurationProperty("Value")]
  public string Value
  {
    get { return (string)this["Value"]; }
    set { this["Value"] = value; }
  }
}
and adding it :
C#:
DirectoryServerConfiguration configData = new DirectoryServerConfiguration();

configData.Key = "YPSAddress";
configData.Value = "My Https Ip";

Configuration configsect = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// You need to remove the old settings object before you can replace it
configsect.Sections.Remove("DirectoryServerConfiguration");
// with an updated one
configsect.Sections.Add("DirectoryServerConfiguration", configData);
// Write the new configuration data to the XML file
configsect.Save();
But I can't make it work, what I am not understanding?
 
Last edited by a moderator:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,983
Location
Chesapeake, VA
Programming Experience
10+
Try configsect.Save(ConfigurationSaveMode.All, false). I'm not at machine where I can do some testing right now, but I relatively recently ran into something similar with regards to web.config files.
 
Top Bottom