您的位置:首页 > 移动开发

C# 通过窗体修改配置文件的代码 App.config

2011-02-25 10:18 579 查看
因为配置文件是用XML写的,而我又没接触所以这个问题是问别人帮忙解决的。觉得方法可行就写出来大家分享方当然其中有很多是需要修改的东西。

public static void SetValue(string AppKey, string AppValue) //传2个参数 一个是配置文件键的名字,一个是要给这个键的值
{

try
{
XmlDocument xDoc = new XmlDocument();     //定义XmlDocument,想操作xml一般都用这个类
//获取App.config文件绝对路径
string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;  //这是获取配置文件路径的
str = str.Substring(0, str.Length - 10) + "App.config"; //这是获取配置文件的名称
//
//上面两行可以直接换成   str =  "你的配置文件.config"的路径
xDoc.Load(str); //读取xml
XmlNode xNode;     //xml节点
XmlElement xElem1;  //xml元素
XmlElement xElem2;  //xml元素
xNode = xDoc.SelectSingleNode("//add");  //获取节点  appSettings 标签的节点
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']"); //获取你要修改的键  AppKey 就是名称或者id
if (xElem1 != null)
xElem1.SetAttribute("connectionString", AppValue);           //如果有这个键就给他赋值  AppValue 就是值
else
{                                                               //没有这个键就添加一个键并且赋值
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("name", AppKey);
xElem2.SetAttribute("connectionString", AppValue);
xElem2.SetAttribute("providerName", "System.Data.SqlClient");
xNode.AppendChild(xElem2);                                              //追加节点,你不用管
}
xDoc.Save(str);
}
catch (Exception e)
{
string error = e.Message;       //报错
}

}


注释也很详细,当然可能对于熟悉XML的来说这并不算什么。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: