C# - 手动覆盖配置

标签 c# xml configuration

我正在使用 C# .net

我需要加载外部配置文件(web.config)并覆盖当前配置中所有部分和(每个部分)所有元素的值。

即,覆盖后,状态应该是:

ConfigurationManager.AppSettings = ...the app settings from the web.config read...

所有部分依此类推。

在类似的代码中(或更简单的代码,如果有的话)。

string s = "c:\test\web.config";

Configuration config = ConfigurationManager.OpenExeConfiguration(s);
foreach(ConfigurationSection section in config.sections) {
  // **** What to do here in order to do: ConfigurationManager.Override(section)
  // so, I can use, i.e, line code such as : string s = ConfigurationManager.AppSettings["key"] ?
}

谢谢。

最佳答案

我找到了解决方案,我想参与其中。

这是代码:

// For the file name:
string s = "c:\test\web.config";

// Now creating configuration:
Configuration roamingConfig =
    ConfigurationManager.OpenExeConfiguration(s);

// configure the map
ExeConfigurationFileMap configFileMap =
    new ExeConfigurationFileMap();

configFileMap.ExeConfigFileName = s;

// Now add new configuration, based on the configuration file map.
Configuration configFile = 
    ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

var allKeys = configFile.AppSettings.Settings.AllKeys;
foreach (var key in allKeys) {
  ConfigurationManager.AppSettings["key"] = 
     configFile.AppSettings.Settings[key].value;
}

configFile.SaveAs(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");

我简单地做的是声明配置两次(第二次使用 map exe 配置打开),将文件保存到其 native 执行路径,然后刷新配置部分 appSettings

关于C# - 手动覆盖配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60187929/

相关文章:

c# - 一个web应用场景中NHibernate乐观并发的问题

c# - 如何从 ImageButton-Click 获取 RepeaterItem 的 ItemIndex?

database - Etherpad - PostgreSQL 错误 : language "plpgsql" does not exist

configuration - 在哪里更改 PhpStorm 选项卡行中文件名的颜色?

c# - IQueryable 对两个唯一 id 匹配的金额求和 C#

c# - 无法更改所选选项

java - Tomcat Web 应用程序不工作

android - 数字不出现在 ADT 编辑器的 XML 文件中

c - 一个简单的 C XML 解析器

php - 尝试运行Behat测试时出错。 usr/bin/env参数无效