【发布时间】:2013-05-13 14:30:47
【问题描述】:
我需要从 app/web.config 中的自定义部分读取键值。
我经历过
Reading a key from the Web.Config using ConfigurationManager
和
How can I retrieve list of custom configuration sections in the .config file using C#?
但是,当我们需要明确指定配置文件的路径(在我的例子中,配置文件不在其默认位置)时,它们没有指定如何读取自定义部分
我的 web.config 文件示例:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MyCustomTag>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</MyCustomTag>
<system.web>
<compilation related data />
</system.web>
</configuration>
其中我需要读取 MyCustomTag 中的键值对。
当我尝试时(configFilePath 是我的配置文件的路径):-
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
return section[keyName].Value;
我在 [keyName] 部分收到一条错误消息,指出“无法在此处访问受保护的内部索引器 'this'”
【问题讨论】:
-
请添加您的 web.config(完整或部分)。
-
与web.config中自定义设置的路径无关。你将使用
<MyCustomTag configSource="customConfig.config" /> -
@FrancescoDeLisi 问题已编辑。
-
@saravanan 在这种情况下,customConfig 是什么?
-
@user85030:该文件将包含您在
<add ...中的所有<add ...元素<MyCustomTag>