我有一个用于多个项目的配置文件,general.config
,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="mykey1" value="myvalue1"/>
<add key="mykey2" value="myvalue2"/>
</appSettings>
在其中一个项目中,我需要覆盖两个设置之一。所以这个项目的 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>
但是 remove
在这里不起作用。如何在不破坏 mykey2
的情况下覆盖 mykey1
? add
在这种情况下有效。我可以从 ConfigurationManager
获取 myvalue3
。
编辑: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
最佳答案
我的一个 friend 回答了这个问题。来自 MSDN :
You can use the file attribute to specify a configuration file that provides additional settings or overrides the settings that are specified in the appSettings element. You can use the file attribute in source control team development scenarios, such as when a user wants to override the project settings that are specified in an application configuration file. Configuration files that are specified in a file attribute must have the appSettings element rather than configuration element as the root node.
所以在这个问题中,general.config
中的设置覆盖了 app.config
中的项目,与我认为(想要)app.config
项目覆盖 general.config
中的项目。现在我想我必须在 C# 代码中解决这个问题(它不可避免地看起来很丑)。
关于c# - 覆盖配置设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6516352/