C# 在Machine.config和App.config中存储相同的密钥
我在machine.config中保留一个自定义配置部分,其结构如下:C# 在Machine.config和App.config中存储相同的密钥,c#,configurationmanager,configurationelement,configsection,C#,Configurationmanager,Configurationelement,Configsection,我在machine.config中保留一个自定义配置部分,其结构如下: <CustomSettings> <add key="testkey" local="localkey1" dev="devkey" prod="prodkey"/> </CustomSettings> 我收到一个错误,说明已添加密钥: 已添加条目“testkey”。 我修改了ConfigElementCollection.Add函数,以检查同一个键是否已经存在,但不起作用 有什么
<CustomSettings>
<add key="testkey" local="localkey1" dev="devkey" prod="prodkey"/>
</CustomSettings>
我收到一个错误,说明已添加密钥:
已添加条目“testkey”。
我修改了ConfigElementCollection.Add函数,以检查同一个键是否已经存在,但不起作用
有什么想法吗?您应该先删除该键,然后再试一次
<CustomSettings>
<remove key="testkey"/>
<add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>
这就应该做到了我最终在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);
}
}
我希望它有帮助……但这不会“合并”这些值。我将只得到dev=devkey1,prod=prodkey1,并将丢失machine.config设置。是的,您将释放它们,可能将它们拆分为不同的键,然后逐个读取它们,您要覆盖的那些可以删除
<CustomSettings>
<remove key="testkey"/>
<add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>
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);
}
}