• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
he dream rolls on from here!I believe in me
我相信我自己!梦想从这里开始
博客园    首页    新随笔    联系   管理    订阅  订阅

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替换这么简单

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

posted @ 2011-08-09 15:15  Star_liu  阅读(1498)  评论(4)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3