c# – app.config中的设置何时实际读取?
发布时间:2020-12-15 08:01:29 所属栏目:百科 来源:网络整理
导读:app.config的设置何时实际由应用程序读取? 假设我有一个Windows服务和一些应用程序设置.在代码中我有一个方法,其中使用了一些设置.在每次迭代中调用方法,而不是在所有时间内调用一次.如果我通过配置文件更改设置值,我是否应重新启动服务以使其在内部“刷新
app.config的设置何时实际由应用程序读取?
假设我有一个Windows服务和一些应用程序设置.在代码中我有一个方法,其中使用了一些设置.在每次迭代中调用方法,而不是在所有时间内调用一次.如果我通过配置文件更改设置值,我是否应重新启动服务以使其在内部“刷新”,或者在下次没有任何交互的情况下接受它? 解决方法
您需要调用
ConfigurationManager.RefreshSection方法以获取直接从磁盘读取的最新值.这是测试和回答问题的简单方法:
static void Main(string[] args) { while (true) { // There is no need to restart you application to get latest values. // Calling this method forces the reading of the setting directly from the config. ConfigurationManager.RefreshSection("appSettings"); Console.WriteLine(ConfigurationManager.AppSettings["myKey"]); // Or if you're using the Settings class. Properties.Settings.Default.Reload(); Console.WriteLine(Properties.Settings.Default.MyTestSetting); // Sleep to have time to change the setting and verify. Thread.Sleep(10000); } } 我的app.config包含: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" > <section name="ConsoleApplication2.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <appSettings> <add key="myKey" value="Original Value"/> </appSettings> <userSettings> <ConsoleApplication2.Properties.Settings> <setting name="MyTestSetting" serializeAs="String"> <value>Original Value</value> </setting> </ConsoleApplication2.Properties.Settings> </userSettings> </configuration> 启动应用程序后,打开build文件夹中的app.config,然后更改appSetting“myKey”的值.您将看到打印到控制台的新值. 要回答这个问题,是的,我们会在第一次读取它们时缓存它们,并且要从磁盘强制读取,您需要刷新该部分. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |