2017-02-24 25 views
1

我知道類似的問題被多次詢問過。我閱讀了一些答案,但沒有爲我的問題找到明確的答案。爲了這一點,我的兩個應用程序說一個& B.應用程序A有一個配置文件,如下所示:C#如何修改其他應用程序的配置文件並保存更改?

<?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> 

應用B試圖修改應用程序的 「KEY0」 配置文件:

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.dll中發生未處理的類型爲'System.Configuration.ConfigurationErrorsException'的異常 附加信息:ro上的數據等級無效。行1,位置1.

我該怎麼做?我錯過了非常明顯的事情嗎?如果有人能指出我正確的方向,我會很感激。

+0

這聽起來像文件沒有正確的xml在它 – Jonesopolis

回答

2

噢,您正在將您的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"); 

然後保存。

+0

不應該它實際上是「csharptesting.exe.config」 – Kevin

+0

是的。好決定。只需將它指向以.config結尾的文件即可。darnit – Jonesopolis

+0

好的,添加.config文件可以消除錯誤,但仍不會將「098」值保存到「Key0」應用程序配置文件。想法?無論如何感謝以上。 – cott

相關問題