微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – app.config中的设置何时实际读取?

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”的值.您将看到打印到控制台的新值.

要回答这个问题,是的,我们会在第一次读取它们时缓存它们,并且要从磁盘强制读取,您需要刷新该部分.

原文地址:https://www.jb51.cc/csharp/100353.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐