【问题标题】:How to add elements to Web.config at runtime如何在运行时向 Web.config 添加元素
【发布时间】:2017-10-28 11:30:48
【问题描述】:

我知道我可以执行以下操作来将键添加到 AppSettings 部分:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("OS", "Linux");
config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

但我想在 <appSettings> 节点之外添加另一个节点,所以它看起来像下面这样:

<appSettings>
</appSettings>
<myCustomSetting firstValue="value1" secondValue="value2"/>

如何在 c# 中做到这一点?

【问题讨论】:

  • 不建议更改 web.config 并且它有它自己的复杂性......您的要求究竟是什么迫使您在运行时修改 web.config 文件?
  • 实际上我动态添加的设置应该作为环境变量参数的一部分从弹性 beanstalk (AWS) 推送。它将被放置在 web.config 文件的 AppSetting 部分中。所以我别无选择,只能将其从应用设置复制到新节点

标签: c# .net web-config configurationmanager


【解决方案1】:

你可以这样做,

var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

var nodeRegion = xmlDoc.CreateElement("myCustomSetting ");
nodeRegion.SetAttribute("firstValue", "value1");
nodeRegion.SetAttribute("secondValue", "value2");

xmlDoc.SelectSingleNode("//myCustomSetting").AppendChild(nodeRegion);
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

你可以在这里发红Update custom configuration sections

【讨论】:

  • 执行时抛出对象引用空错误:xmlDoc.SelectSingleNode("//myCustomSetting").AppendChild(nodeRegion);
  • 将其更改为 xmlDoc.SelectSingleNode("//configuration").AppendChild(nod‌​eRegion);因为我应该在配置节点中添加我的自定义设置节点。
猜你喜欢
  • 1970-01-01
  • 2015-11-10
  • 2019-07-11
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多