2013-07-21 133 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

相关问题