![](/img/trans.png)
[英]How do I in C# modify an Excel spreadsheet, save it as another name and delete the original spreadsheet
[英]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嘗試修改App A配置文件的“ 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'的未處理異常。其他信息:根級別的數據無效。 第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");
然后保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.