c# - .Net 配置 - 如何覆盖映射配置文件中的设置和自定义部分?

标签 c# .net configuration app-config

如果我在 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->app 配置文件优先级一样? (甚至 machine.config -> machine root web.config -> local app 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

最佳答案

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

否则,我不相信这是可能的。特别是配置转换的灵 active 。

关于c# - .Net 配置 - 如何覆盖映射配置文件中的设置和自定义部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9696271/

相关文章:

python - Nginx 在静态文件上抛出 403 Forbidden

php - Doctrine ODM 在运行时选择数据库

c# - 如何在 C# 单元测试中涵盖图像转换?

c# - OnModelCreating 的目的 - EF Core 数据库优先方法

c# - 第一次反序列化比后续反序列化花费的时间要长得多

c# - Try-catch 加速我的代码?

configuration - 本地Kibana未连接到本地Elasticsearch Server(StreamCorruptedException?)

C# 获取 XML 标记值

c# - 在 DirectX 中渲染环境

c# - 等于 System.Collections.Generic.List<T>... 的方法?