C#中动态更改App.config中的连接字符串
前几天做了个项目,需要是客户端通过更改ip来实现读取服务器端的数据库
通过我的实验!原来这样是需要通过更改连接字符串来实现这样的功能,而且在程序中不能出现绝对路径!
我的app.config是这个样子的
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="constr" connectionString="server=*********;Database=*********;Persist Security Info=True;User ID=***;Password=***;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
先解释一下:server=这个是服务器的ip地址,database是服务器端的数据库名 User ID和Password这个就不做解释了
前台更改的窗口是这样的
从上到下依次是TextBox1 TextBox2 TextBox3 和TextBox4
下面就是怎么替换了
string newName = "constr";
string newConString = "server="+textBox1.Text.Trim()+";Database="+textBox2.Text.Trim()+";Persist Security Info=True;User ID="+textBox3.Text.Trim()+";Password="+textBox4.Text.Trim()+";";
string newProviderName = "System.Data.SqlClient";
//首先要登录进xml中也就是appconfig
XmlDataDocument doc = new XmlDataDocument();
string path = "";//安装包制作时候的路径,这里先用这个文件的路径代替
string nowpath = System.Windows.Forms.Application.ExecutablePath + ".config";
doc.Load(nowpath);
MessageBox.Show(newConString);
XmlNode node = doc.SelectSingleNode("//connectionStrings");//获取connectionStrings节点
try
{
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + newName+ "']");
if (element != null)
{
//存在更新子节点
element.SetAttribute("connectionString", newConString);
}
else
{
}
doc.Save(nowpath);
}
catch (InvalidCastException ex)
{
throw ex;
}
add节点里面的name和providerName是不需要变动的
总结:因为app.config是一个xml文件所以这里面涉及到的就是xml替换这么简单
我写这博文只是为了让自己记忆更深刻一下!各位大虾如果看到有错误或者是写的不妥当的地方麻烦你帮我指出来!在这先谢谢了