【问题标题】:.Net configuration - How to override settings and custom sections in a mapped configuration file?.Net 配置 - 如何覆盖映射配置文件中的设置和自定义部分?
【发布时间】:2012-03-30 13:49:50
【问题描述】:

如果我在 myprogram.exe.config 文件中有:

<configuration>
  <configSections>
    <section name="fooSection" type="MyNamespace.MySection, My.Assembly"/>
  </configSections>
  <appSettings>
    <add key="foo" value="bar"/>
  </appSettings>
  <fooSection>
    <bar>
      <add baz="foo bar baz"/>
    </bar>
  </fooSection>
</configuration>

我在 overrides.config 文件中有:

<configuration>
  <configSections>
    <section name="fooSection" type="MyNamespace.MySection, My.Assembly"/>
  </configSections>
  <appSettings>
    <add key="foo" value="BAZ"/>
  </appSettings>
  <fooSection>
    <bar>
      <add baz2="foo foo"/>
    </bar>
  </fooSection>
</configuration>

有什么方法可以将这个读入核心(或加载的)配置,就像你会得到机器->应用程序配置文件优先级一样? (甚至 machine.config -> 机器根 web.config -> 本地应用程序 web.config)

在本例中,我希望 config.AppSettings["foo"] 为“BAZ”,而 fooSection 包含两个项目:“foo bar baz”和“foo foo”。

我找不到方法,我猜它可能不受支持。我尝试了很多排列方式。

MySection section = ConfigurationManager.GetSection("foo") as MySection;

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.LocalUserConfigFilename = // have tried this;
fileMap.ExeConfigFilename = // have tried this
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
ConfigurationManager.RefreshSection("foo");

foo = ConfigurationManager.GetSection("foo") as MySection;
// will only have one item
foo = config.GetSection("foo") as MySection;
// will only have one item

【问题讨论】:

  • 你曾经解决过这个问题吗?我有类似的要求,我必须用客户端特定的配置覆盖默认配置。

标签: c# .net configuration app-config


【解决方案1】:

您为什么要这样做?这在我看来就像您正在尝试处理生产配置?如果是这种情况,那么我建议查看 .config 转换。事实上,Scott Hanselman 写了一个good post on the subject

否则,我认为这是不可能的。尤其是配置转换的灵活性。

【讨论】:

  • 谢谢,贾斯汀。这在某些情况下可能很有用。现在我运行产品的回归测试,并且可以指定 -config path\to.config 来测试某些功能,因此构建理念的改变可能会使其适合。
  • 另一种情况是,程序可能不是从本地路径运行,而是从网络共享(更容易分发软件)运行。例如,它作为控制台应用程序或 Windows 服务运行 - 您可以指定命令行选项,或直接指向为本地主机量身定制的配置文件。
  • 希望对您有所帮助,stackoverflow.com/questions/9826744/…>
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 2022-10-14
  • 2023-02-15
  • 1970-01-01
相关资源
最近更新 更多