我在以下结构的machine.config中持有自定义配置部分:
<CustomSettings>
<add key="testkey" local="localkey1" dev="devkey" prod="prodkey"/>
</CustomSettings>
现在,我希望能够通过在app.config中存储覆盖来覆盖相同的密钥设置,如下所示:
<CustomSettings>
<add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>
所以,当我在代码中读到它时,我会得到 - dev =“devkey1”,prod =“prodkey1”, local =“localkey1”
问题是,当我读取我的自定义配置部分时:
CustomConfigurationSection section = ConfigurationManager.GetSection("CustomSettings") as CustomConfigurationSection;
我收到一条错误消息,指出该密钥已被添加:
“已添加条目'testkey'。”
我修改了 ConfigElementCollection.Add 函数来检查相同的密钥是否已经存在但是它不起作用。
有什么想法吗?
答案 0 :(得分:0)
您应首先删除密钥,然后尝试
<CustomSettings>
<remove key="testkey"/>
<add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>
应该做的伎俩
答案 1 :(得分:0)
我最终覆盖了ConfigurationElementCollection中的BaseAdd:
protected override void BaseAdd(ConfigurationElement element)
{
CustomConfigurationElement newElement = element as CustomConfigurationElement;
if (base.BaseGetAllKeys().Where(a => (string)a == newElement.Key).Count() > 0)
{
CustomConfigurationElement currElement = this.BaseGet(newElement.Key) as CustomConfigurationElement;
if (!string.IsNullOrEmpty(newElement.Local))
currElement.Local = newElement.Local;
if (!string.IsNullOrEmpty(newElement.Dev))
currElement.Dev = newElement.Dev;
if (!string.IsNullOrEmpty(newElement.Prod))
currElement.Prod = newElement.Prod;
}
else
{
base.BaseAdd(element);
}
}
我希望它有所帮助...