从 c# 方法更新 App.Config

Updating App.Config from c# method

我正在尝试使用以下代码从 windows 表单

更新我的应用程序配置
public void UpdateConfigFile(string con)
        {
            //updating config file
            XmlDocument xmlDoc = new XmlDocument();        
            //Loading the Config file
            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            if (xmlDoc.DocumentElement != null)
                foreach (XmlElement xElement in xmlDoc.DocumentElement)
                {
                    if (xElement.Name == "connectionStrings")
                    {
                        //setting the coonection string
                        if (xElement.FirstChild.Attributes != null) xElement.FirstChild.Attributes[2].Value = con;
                    }
                }
            //writing the connection string in config file
            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

不确定我是否遗漏了重点,但我希望在我的解决方案中看到 app.config 文件更新。但是代码实际上更新了我的 C:\Users\temp\Documents\Visual Studio 2010\Projects\SequoiaToolbox2014MvvM\SequoiaToolbox2014MvvM\bin\Debug\SequoiaToolbox2014MvvM.vshost.exe.config 并且对 app.con 文件没有影响?

您正在构建并且 运行 从调试模式。默认情况下,调试模式使用 VSHost .exe 和 .config 来缩短启动时间和调试时间。由于它正在更新此临时文件,因此您没有看到预期文件中的更改。

要让它正常工作,您需要做以下两件事之一:

  1. 运行 处于发布模式
  2. 按照 MSDN article:
  3. 中的指导关闭此行为

To disable the hosting process

  1. Open an executable project in Visual Studio. Projects that do not produce executables (for example, class library or service projects) do not have this option.
  2. On the Project menu, click Properties.
  3. Click the Debug tab.
  4. Clear the Enable the Visual Studio hosting process check box.

When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.