且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时更改 App.config

更新时间:2022-11-04 15:01:30

UPDATE

下面的解决方案不起作用,因为 XmlDocument 没有处理,而且在给定文件路径时,某些版本的 .net 似乎没有正确关闭.解决方案(链接中的示例代码)是打开一个流,该流将执行处置并将该流传递给保存函数.

The solution below did not work because XmlDocument does not dispose and it seems some versions of .net do not close correctly when given a file path. The solution (example code in the link) is to open a stream which will do a dispose and pass that stream to the save function.

此处显示了解决方案.http://web-beta.archive.org/web/20150107004558/www.devnewsgroups.net/group/microsoft.public.dotnet.xml/topic40736.aspx

下面的旧东西

试试这个:

注意,我改成了 xpath,但已经有一段时间了,所以我可能把 xpath 弄错了,但无论如何你应该使用 xpath 而不是遍历树.正如你所看到的那样清晰得多.

Note, I changed to xpath, but it has been a while so I might have gotten the xpath wrong, but in any case you should use xpath and not walk the tree. As you can see it is much clearer.

重点是 using 语句,它将 dispose(),我认为这是你的问题.

The important point is the using statement which will dispose(), which I think was your problem.

告诉我,祝你好运.

  public void UpdateAppSettings(string key, string value)
  {
    using (XmlDocument xmlDoc = new XmlDocument())
    {
      xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
      xmlDoc.DocumentElement.FirstChild.SelectSingleNode("descendant::"+key).Attributes[0].Value = value;
      xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
    System.Configuration.ConfigurationManager.RefreshSection("section/subSection");
  }