C#中动态更改App.config中的连接字符串

本文介绍了一种在客户端通过修改IP地址实现读取服务器数据库的方法,重点在于如何动态更改app.config文件中的数据库连接字符串,避免使用绝对路径,通过XML替换技术实现连接信息的更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前几天做了个项目,需要是客户端通过更改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替换这么简单

我写这博文只是为了让自己记忆更深刻一下!各位大虾如果看到有错误或者是写的不妥当的地方麻烦你帮我指出来!在这先谢谢了

转载于:https://www.cnblogs.com/Star-myfly/archive/2011/08/09/2132324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值