app.config的設置實際上是由應用程序讀取的嗎?app.config的設置何時實際讀取?
假設我有一個Windows服務和一些應用程序設置。在代碼中,我有一個使用某些設置的方法。每次迭代都會調用方法,而不是一直在調用一次。如果我通過配置文件更改了設置值,我應該重新啓動服務,以便在內部進行「刷新」或在下次沒有任何交互時接受服務?
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, System, Version=4.0.0.0, Culture=neutral, 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」的值。您會看到打印到控制檯的新值。
要回答這個問題,是的,他們是第一次緩存他們每次讀我認爲,並強制直接從磁盤讀取,你需要刷新部分。
要麼通過配置管理器(ConfigurationManager.GetSection(「x/y」);)加載它,要麼嘗試訪問屬性。
這裏有一個輕微的灰色地帶,因爲當您通過配置管理器獲取配置了:
var config = (MyConfigSection)ConfigurationManager.GetSection("MyConfigSection");
你得到一個配置對象回來,如果你已經在提供的configurationSections元素的配置部分類型配置文件的頂部。如果你實際上沒有提供實際的配置,你仍然會得到一個對象。
但是,如果您有一個未設置的必填字段,它將不會拋出異常,直到您致電屬性。我嘗試過單元測試自定義配置部分的時候已經完成了這個工作。
如果我得到如下設置:Properties.Settings.Default.MyValue? – 26071986 2012-02-08 18:17:16
使用Properties.Settings.Default.Reload(); – mservidio 2012-02-08 18:18:31
@ 26071986 - 我更新了我的答案以反映使用Settings類時的代碼。 – mservidio 2012-02-08 18:25:46