2013-07-21 238 views
6

我試圖創建一個基於AppSettings的自定義配置文件部分:ConfigurationManager.GetSection和Configuration.GetSection之間有什麼不同?

<configSections> 
    <section name="customConfiguration" 
      type="System.Configuration.AppSettingsSection, 
       System.Configuration, 
       Version=2.0.0.0, Culture=neutral, 
       PublicKeyToken=b03f5f7f11d50a3a"/> 
</configSections> 

,當我試圖通過ConfigurationManager.GetSection閱讀它(「customConfiguration」)返回的對象是類型System.Configuration.KeyValueInternalCollection的。我無法讀取該集合的值,但我能看到的鑰匙,我無法將其轉換爲AppSettingsSection。

This#1回答提示我應該使用

Configuration config = 
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
AppSettingsSection customSettingSection = 
    (AppSettingsSection)config.GetSection("customConfiguration"); 

這個工作。我的問題是:ConfigurationManager.GetSection()和Configuration.GetSection()之間有什麼區別?我什麼時候應該使用一個,什麼時候應該使用另一個?

回答

5

根據對配置類http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx MSDN文檔,

如果您的應用需求只讀到自己的配置訪問,推薦您使用Web應用程序的GetSection方法重載。對於客戶端應用程序,請使用GetSection方法。

這些方法提供訪問緩存的配置值當前應用程序,它具有比配置類更好的性能。

具體來說,在客戶端應用程序中,ConfigurationManager檢索通過合併應用程序配置文件,本地用戶配置文件和漫遊配置文件獲得的配置文件。

+0

所以Configuration.GetSection是客戶端應用程序,讓指定的用戶配置的部分(適用於所有用戶,當前用戶的本地配置文件或當前用戶的漫遊配置文件,這取決於OpenExeConfiguration指定的ConfigurationUserLevel)?而ConfigurationManager.GetSection得到默認配置的部分,這對於客戶端應用程序是所有三個用戶配置(所有用戶,當前用戶的本地配置文件,當前用戶的漫遊配置文件)的合併組合?那麼爲什麼兩個GetSection方法返回不同的對象類型呢? –

+1

'System.Configuration.GetSection()'是通用的,可以同時用於網絡和客戶機應用程序,而'ConfigurationManager.GetSection()'是用於優化客戶端的包裝APPS特異性。 – Claies

+0

@Claies這是否意味着存在使用無默認方式'ConfigurationManager.OpenMappedExeConfiguration()'打開一個不同的配置文件,並把它通過使用其返回'Configuration.GetSection()表現良好'加載部分。由於只有'ConfigurationManager.GetSection()'「表現良好」,但它使用應用程序的默認配置 – FRoZeN

相關問題