动态编辑程序配置文件
1
using System;2
using System.Collections.Generic;3
using System.ComponentModel;4
using System.Data;5
using System.Drawing;6
using System.Linq;7
using System.Text;8
using System.Windows.Forms;9
using System.Xml;10

11
namespace WindowsFormsApplication112


{13
public partial class Form1 : Form14

{15
public Form1()16

{17
InitializeComponent();18
}19

20
private void button1_Click(object sender, EventArgs e)21

{22
SaveConfig("welcome");23
}24

/**//// <summary>25
/// 设置配置文件26
/// </summary>27
/// <param name="ConnenctionString"></param>28
private void SaveConfig(string ConnenctionString)29

{30
XmlDocument doc=new XmlDocument();31
//获得配置文件的全路径32
string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "WindowsFormsApplication1.exe.config";33
doc.Load(strFileName);34
//找出名称为“add”的所有元素35
XmlNodeList nodes = doc.GetElementsByTagName("add");36

/**////这里修改原结点37
for (int i = 0; i < nodes.Count; i++)38

{39
//获得将当前元素的key属性40
XmlAttribute att = nodes[i].Attributes["name"];41
42
//根据元素的第一个属性来判断当前的元素是不是目标元素43
if (att.Value == "my")44

{45
//对目标元素中的第二个属性赋值46
att = nodes[i].Attributes["connectionString"];47
att.Value = ConnenctionString;48
break;49
}50
}51

52

/**////这里新加结点53
nodes = doc.GetElementsByTagName("connectionStrings");54
for (int i = 0; i < nodes.Count; i++)55

{56
XmlNode nd = nodes[i];57
XmlNode cnd = null;58
if (nd.HasChildNodes)59

{60
cnd = nd.ChildNodes[i].Clone();61
cnd.Attributes["name"].Value = "newvalue";62
cnd.Attributes["connectionString"].Value = "heelo!";63
}64
65
66
nd.AppendChild(cnd);67
68
}69
//保存上面的修改70
doc.Save(strFileName);71
}72

73
}74
}75

这里和大家分享和学习如何学IT!

浙公网安备 33010602011771号