【问题标题】:Store same key in Machine.config and App.config在 Machine.config 和 App.config 中存储相同的密钥
【发布时间】:2013-04-23 16:30:20
【问题描述】:

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

有什么想法吗?

【问题讨论】:

    标签: c# configurationmanager configurationelement configsection


    【解决方案1】:

    你应该先删除密钥,试试

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

    这应该可以解决问题

    【讨论】:

    • 但这不会“合并”这些值。我最终只会得到 dev=devkey1, prod=prodkey1 并且会丢失 machine.config 设置。
    • 是的,你会松开它们,也许把它们分成不同的键,然后一一读取,你想覆盖的你可以删除
    【解决方案2】:

    我最终在 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);
          }
        }
    

    希望对你有帮助……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      相关资源
      最近更新 更多