c# - 覆盖配置设置

标签 c# .net configuration app-config

我有一个用于多个项目的配置文件,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 的情况下覆盖 mykey1add 在这种情况下有效。我可以从 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/

相关文章:

c# - 当 DropDownStyle 为 Simple 时,ToolStripCombobox 显示在屏幕左上角

c# - 结合MVVM、ORM和一些硬件接口(interface)

c# - 获取由 Windows 快捷方式配置的正确窗口样式

.net - 有没有办法通过MonoTouch制作 "custom" map ?

c# - 定期从 EF 中的多个线程更新实体

c# - Entity Framework 依赖注入(inject)

C# .NET 将 JPEG 图像转换为位图结构

perl - 所有 CPAN 镜像都不能在 CPAN 配置中工作?

java - 不同上下文中的 Spring bean 连接

tomcat - 收集 RELOAD 后 SolrCloud 节点关闭