如何将web.config的appSettings获取为ConfigurationSection而不是NameValueCollection

10
ConfigurationManager.AppSettings属性返回一个NameValueCollection对象,该对象包含当前应用程序默认配置的AppSettingsSection对象的内容。
但我需要AppSettingsSection对象,因为我需要在运行时更改它的configSource属性。
2个回答

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

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);

2
无法将类型为'System.Configuration.KeyValueInternalCollection'的对象转换为类型'System.Configuration.AppSettingsSection'。 - Bohdan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接