Change in AppSettings needs restart my Application how can I avoid?

久未见 提交于 2019-12-04 11:18:33

问题


I'm using C# .NET 2.0 Windows Application.

and I'm using app.config for my Application Settings.

but change in AppSettings doesn't reflected runtime, it Needs Application to be restarted.

How can I avoid it.

Here is my code snippet I used to read and write the Application Settings.

I'm reading the Setting like this

string temp = ConfigurationManager.AppSettings.Get(key);

I'm updating the value like this where node is the current configuration/appSettings Node

node.Attributes["value"].Value = value;
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

回答1:


You could try calling

ConfigurationManager.RefreshSection("appSettings")
to refresh the AppSettings section of the file from disk. Once they have been refreshed, you should be able to read the new values.

I've just tested this and it does indeed work.




回答2:


Alternatively, you could create a singleton 'Options' to hold on to your application settings and perform your read/writes for you. Once loaded, changing the .config doesn't require reloading, you simply set a property on the singleton and call your .Save() method.

The 'runtime' version of your settings is in the singleton, no need to read from disk.




回答3:


Dont use ConfigurationManager to read settings, instead use:

        System.Configuration.ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).AppSettings.Settings["value"];



回答4:


ConfigurationManager.RefreshSection("appSettings");

works!!

But be careful that if we are in debug mode, the configuration file can be called xxxxx.vshost.exe.config, where xxxxx is your project name.



来源:https://stackoverflow.com/questions/1254677/change-in-appsettings-needs-restart-my-application-how-can-i-avoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!