问题
I have a appsetting section in appconfig file as
<appSettings>
<add key="DayTime" value="08-20"/>
<add key="NightTime" value="20-08"/>
</appSettings>
I am tyring to modify the app config while application is running. I changed key DayTime to 11-20 while application is running.
Now if I run this code again to fetch data from config, it shows previous set values.
private void btnDayNightSettings_ShowingEditor(object sender, ItemCancelEventArgs e)
{
string[] strDayTime = ConfigurationManager.AppSettings["DayTime"].Split('-');
}
Why it is so ?
回答1:
The reason behind why the AppSetting section in app.config file is not getting reflected during update in Run time is as follows:
- When you add a new app.config file it actually creates a file in the local system.
- When you compile it, actually it creates the necessary files including
.Exefiles inDebug/Releasefolder; depending upon the Build mode. - After successful build it also generates a
.configfile which looks likeYourApplicationName.exe.configwhich holds the same entries in original app.config file. And the.Exealways refers to this file. - So whenever you edit the
app.configat Runtime it actually updates the file but changes are not updated inYourApplicationName.exe.configfile as it has not re-build yet.
So every time you need to re-build to your app to reflect the changes.
回答2:
I have my own answer. Just need to refresh appSettings section as
ConfigurationManager.RefreshSection("appSettings");
回答3:
app.config is cached, the changes will reflect when you restart the application. See is app.config file in WinForms cached by .Net framework?
回答4:
Try this:
string strDayTime = ConfigurationManager.AppSettings["DayTime"];
ConfigurationManager.AppSettings.Set("DayTime", "11-20");
strDayTime = ConfigurationManager.AppSettings["DayTime"];
The value of the strDayTime variables changes on both lines.
来源:https://stackoverflow.com/questions/16855043/app-config-modification-not-reflected-in-code