博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Winform程序修改*.exe.config文件

Posted on 2007-11-14 09:14  迷梦江南  阅读(3493)  评论(0编辑  收藏  举报
程序打包安装后,一般都要修改数据库的连接字符串,如果用个小程序来修改字符串,用户会更容易接受些。我做了个小示例。

App.config文件:

<?xmlversion="1.0"encoding="utf-8"?>

<configuration>

 <appSettings>

    <addkey="123"value="sf" />

 </appSettings>

</configuration>

界面:

CS代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Configuration;

using System.Xml;

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        protected override void OnLoad(EventArgs e)

        {

            base.OnLoad(e);

            label1.Text = "当前连接字符串:" + ConfigurationSettings.AppSettings["123"].ToString();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            string newConsting = textBox1.Text.Trim();

            XmlDocument xmlDoc = new XmlDocument();

            string s = System.Windows.Forms.Application.StartupPath + "/WindowsApplication1.exe.config";

            xmlDoc.Load(s);

            XmlNode node = xmlDoc.SelectSingleNode("//appSettings");

             XmlElement element = (XmlElement)node.SelectSingleNode("//add [@key=""123""]");

             if (element != null)

            {

                element.SetAttribute("value", newConsting);

            }

            xmlDoc.Save(s);

            xmlDoc = null;

            this.Close();

        }

   }

}

运行效果:

点击修改按钮后,重新启动程序可以看见:

要注意的是,我修改的并不是App.config里面的连接字符串,所以当程序重新生成的时候,App.config文件里面的连接字符串会把WindowsApplication1.exe.config里面的字符串覆盖掉。