0

我在 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函数来检查相同的键是否已经存在但它不起作用。

有任何想法吗?

4

2 回答 2

0

你应该先删除密钥,试试

<CustomSettings>
   <remove key="testkey"/>
   <add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings> 

这应该够了吧

于 2013-04-23T17:00:18.863 回答
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);
      }
    }

我希望它有帮助...

于 2013-04-24T10:21:00.053 回答