views:

57

answers:

1

Hi, Ok so im trying to use the appSettings element in the App.Config file to determine what kind of storage to use. Here is my app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="storage" value="memory"/>
  </appSettings>
</configuration>

So I want to change the value of the storage "setting" to "xmlfile", so I wrote this method to change the field following some post I found on the internet:

public static void UpdateAppSettings(string keyName, string keyValue)
{
    XmlDocument doc = new XmlDocument();

    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

    foreach (XmlElement elem in doc.DocumentElement)
    {
        if (elem.Name == "appSettings")
        {
            foreach (XmlNode node in elem.ChildNodes)
            {
                if (node.Attributes[0].Value == keyName)
                {
                    node.Attributes[1].Value = keyValue;
                }
            }
        }
    }
    doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

How ever when I use it, there is no change to the App.Configany ideas on what im doing wrong?

P.S. Just for reference im only using the following simple method to test it:

    Console.WriteLine(ConfigurationManager.AppSettings["storage"].ToString());
    Console.Read();
    AppConfigFileSettings.UpdateAppSettings("storage", "xmlfile");
    Console.WriteLine(ConfigurationManager.AppSettings["storage"].ToString());
    Console.Read();

Which just prints out "memory" twice.

Thanks

+2  A: 

The reason you see that behavior is due the configuration being loaded only once and the subsequent accesses to the application configuration settings are coming from memory.

You can use ConfigurationManager.RefreshSection("appSettings") to refresh the applciation settings section and this way the new value will be loaded into memory.

João Angelo
wow, nice. I didn't know this was possible. So one can change all the config at runtime.
SwissCoder