如何将web.config appSettings作为ConfigurationSection而不是NameValueCollection

时间:2012-06-20 10:24:49

标签: asp.net .net

ConfigurationManager.AppSettings属性 返回一个NameValueCollection对象,该对象包含当前应用程序默认配置的AppSettingsSection对象的内容。

但我需要AppSettingsSection对象,因为我需要在运行时更改它的configSource属性

2 个答案:

答案 0 :(得分:5)

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

答案 1 :(得分:4)

您可以使用Configuration.GetSection方法或Configuration.AppSetting属性获取AppSettingsSection

要获取Configuration对象,您需要使用ConfigurationManager.Open...WebConfigurationManager.Open...方法:

string sectionName = "appSettings";
var config = 
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettingSection =
    (AppSettingsSection)config .GetSection(sectionName);
相关问题