App.config文件:
<?xmlversion="1.0"encoding="utf-8"?>
<configuration>
<appSettings>
<addkey="123"value="sf" />
</appSettings>
</configuration>
界面:
CS代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
label1.Text = "当前连接字符串:" + ConfigurationSettings.AppSettings["123"].ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string newConsting = textBox1.Text.Trim();
XmlDocument xmlDoc = new XmlDocument();
string s = System.Windows.Forms.Application.StartupPath + "/WindowsApplication1.exe.config";
xmlDoc.Load(s);
XmlNode node = xmlDoc.SelectSingleNode("//appSettings");
XmlElement element = (XmlElement)node.SelectSingleNode("//add [@key=""123""]");
if (element != null)
{
element.SetAttribute("value", newConsting);
}
xmlDoc.Save(s);
xmlDoc = null;
this.Close();
}
}
}
运行效果:
点击修改按钮后,重新启动程序可以看见:
要注意的是,我修改的并不是App.config里面的连接字符串,所以当程序重新生成的时候,App.config文件里面的连接字符串会把WindowsApplication1.exe.config里面的字符串覆盖掉。