C# 如何修改另一个应用程序的配置文件并保存更改?

C# How do I modify configuration file of another application and save the change?

我知道以前不止一次问过类似的问题。我阅读了一些答案,但没有找到适合我的问题的明确答案。顺便说一句,我有两个应用程序A和B。应用程序A有一个配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key = "Key0" value = "4567" />
    <add key = "Key1" value = "1" />
    <add key = "Key2" value = "2" />
  </appSettings>
</configuration>

App B 尝试修改 "Key0" 的 App A 配置文件:

namespace ModifyOtherConfig
{
    public partial class Form1 : Form
    {
        string otherConfigFilePath;
        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = @"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe";
            Configuration otherConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);


            string otherSetting = otherConfig.AppSettings.Settings["Key0"].Value;
            MessageBox.Show(otherSetting);
            otherSetting = "098";
            MessageBox.Show(otherSetting);
            otherConfig.SaveAs(fileMap.ExeConfigFilename, ConfigurationSaveMode.Full);
        }
    }
}

当我尝试 运行 此代码时,出现以下错误:

'System.Configuration.ConfigurationErrorsException' 类型的未处理异常发生在 System.Configuration.dll 附加信息:根级别的数据无效。第 1 行,位置 1.

我做错了什么?我错过了一些非常明显的东西吗?如果有人能指出正确的方向,我将不胜感激。

哦,您正在将 fileMap.ExeConfigFilename 指向 .exe,请将其更改为指向 .config 文件。这就是您看到 xml 错误的原因。

fileMap.ExeConfigFilename = @"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe.config";

对于您的其他问题,请执行:

otherConfig.AppSettings.Settings.Remove("Key0");
otherConfig.AppSettings.Settings.Add("Key0", "098");

然后保存。