在运行时更改App.config

bor*_*ula 7 c# configurationmanager app-config configuration-files .net-3.5

我正在为我们正在开发的系统编写测试WinForms/C#/ .NET 3.5应用程序,我们不需要在运行时切换.config文件,但这变成了一场噩梦.

这是场景:WinForms应用程序旨在测试WebApp,分为5个子系统.测试过程适用于在子系统之间发送的消息,并且为了使该过程成功,每个子系统都有自己的.config文件.

对于我的测试应用程序,我写了5个单独的配置文 我希望我能够在运行时在这5个文件之间切换,但问题是:我可以编程方式编辑应用程序.config文件很多次,但这些更改只会生效一次.我一直在寻找一个表格来解决这个问题,但我仍然没有成功.

我知道问题定义可能有点令人困惑,但如果有人帮助我,我会非常感激.

提前致谢!

---更新01-06-10 ---

我之前没有提到过.最初,我们的系统是一个Web应用程序,每个子系统之间都有WCF调用.出于性能测试的原因(我们使用的是ANTS 4),我们必须创建程序集的本地副本并从测试项目中引用它们.听起来有点不对劲,但我们找不到令人满意的方法来衡量远程应用程序的性能.

---结束更新---

这是我正在做的事情:

public void UpdateAppSettings(string key, string value)
{
    XmlDocument xmlDoc = XmlDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

    foreach (XmlElement item in xmlDoc.DocumentElement)
    {
        foreach (XmlNode node in item.ChildNodes)
        {
            if (node.Name == key)
            {
                node.Attributes[0].Value = value;
                break;
            }
        }
    }

    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

    System.Configuration.ConfigurationManager.RefreshSection("section/subSection");    
}
Run Code Online (Sandbox Code Playgroud)

Sud*_*hra 25

我知道这是一个很老的线程,但我无法让列出的方法起作用.这是UpdateAppSettings方法的更简单版本(使用.NET 4.0):

private void UpdateAppSettings(string theKey, string theValue)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ConfigurationManager.AppSettings.AllKeys.Contains(theKey))
            {
                configuration.AppSettings.Settings[theKey].Value = theValue;
            }

            configuration.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("appSettings");
        }
Run Code Online (Sandbox Code Playgroud)

非常易读并且避免使用Xpath等遍历app.config.注意:上面的代码的灵感来自MSDN上的这个代码段.


Hog*_*gan 3

更新

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

这里显示了一个解决方案。http://web-beta.archive.org/web/20150107004558/www.devnewsgroups.net/group/microsoft.public.dotnet.xml/topic40736.aspx


下面是旧东西

尝试这个:

请注意,我更改为 xpath,但已经有一段时间了,所以我可能弄错了 xpath,但无论如何你应该使用 xpath 而不是遍历树。正如您所看到的,它更加清晰。

重要的一点是usingwhich will 的声明dispose(),我认为这是你的问题。

告诉我吧,祝你好运。

  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");
  }
Run Code Online (Sandbox Code Playgroud)