C# 动态修改Web.config
protected void btnSet_Click(object sender, EventArgs e) { XmlDocument xmlDoc=new XmlDocument(); string filename = Server.MapPath("/")+"Web.config"; xmlDoc.Load(filename); XmlNode root = xmlDoc.SelectSingleNode("configuration"); XmlNode conNode = root.SelectSingleNode("connectionStrings"); XmlNodeList conNodeList = conNode.ChildNodes; bool haveconnectionString = false; string constring="data source=" + tbServer.Text.Trim() + ";user="+tbUser.Text.Trim()+";pwd="+tbPwd.Text.Trim()+";Initial Catalog="+tbDB.Text+";"; foreach (XmlNode node in conNodeList) { XmlElement element = (XmlElement)node; //将子节点类型转换为XmlElecment类型 if (element.GetAttribute("providerName") == "System.Data.SqlClient") { element.SetAttribute("connectionString", constring); element.SetAttribute("name", "connectionString1"); haveconnectionString = true; } } if (haveconnectionString == false) { XmlElement xel= xmlDoc.CreateElement("add"); xel.SetAttribute("name", "connectionString1"); xel.SetAttribute("connectionString", constring); xel.SetAttribute("providerName", "System.Data.SqlClient"); conNode.AppendChild(xel); } xmlDoc.Save(filename); }
posted on 2011-01-03 22:30 Henry_Wang 阅读(494) 评论(0) 编辑 收藏 举报