覆盖配置设置

Che*_*hen 10 .net c# configuration app-config

我有一个在几个项目中使用的配置文件general.config,看起来像:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
   <add key="mykey1" value="myvalue1"/>    
   <add key="mykey2" value="myvalue2"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

在其中一个项目中,我需要覆盖两个设置中的一个.所以app.config这个项目看起来像:

<?xml version="1.0"?>
<configuration>
  <appSettings file="general.config">
    <remove key="mykey1"/>
    <add key="mykey1" value="anothervalue"/>
    <add key="mykey3" value="myvalue3"/>
  </appSettings>  
</configuration>
Run Code Online (Sandbox Code Playgroud)

但是remove不在这里工作.如何在mykey1不破坏的情况下覆盖mykey2add适用于这种情况.我可以myvalue3ConfigurationManager.

编辑:general.config编译时自动复制到输出文件夹.不要担心路径问题.目前我得到了:

ConfigurationManager.AppSettings["mykey1"] 
     //I got "myvalue1", but I want "anothervalue" here
     //that is, this item is "overrided", just like virtual methods in C#
ConfigurationManager.AppSettings["mykey2"] 
     //this setting will not be modified, currently it works fine
ConfigurationManager.AppSettings["mykey3"]   //good 
Run Code Online (Sandbox Code Playgroud)

Che*_*hen 4

MSDN帮助回答了这个问题:

您可以使用 file 属性来指定提供其他设置或覆盖 appSettings 元素中指定的设置的配置文件。您可以在源代码管理团队开发方案中使用文件属性,例如当用户想要覆盖应用程序配置文件中指定的项目设置时。文件属性中指定的配置文件必须将 appSettings 元素而不是配置元素作为根节点。

因此,您中的设置general.config将覆盖app.config. 这与您想要的相反(让app.config项目覆盖general.config项目)。您必须在 C# 代码中解决这个问题(它不可避免地看起来很难看)。