Reputation: 5224
OK, so I'm 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.Config. Any ideas on what I'm doing wrong?
P.S.
Just for reference I'm 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.
Upvotes: 4
Views: 2158
Reputation: 57658
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.
Upvotes: 3