您的位置:首页 > 移动开发

WinForm下App.config配置文件的读与写

2008-09-05 21:58 447 查看
WinForm下App.config配置文件的读与写
Woody | 2008-3-5
      先来看下我操作的App.config文件的内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="DbHelper"   connectionString="Server=192.168.0.57;Database=linan98;User ID=sa;Password=sa" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>
       这个我介绍的方法也是参考了以前写过的操作XML文件的方法.
       原理就是:把XML读入dataset,通过dataset的自带的操作XML的方法来实现。
        private void SetValue() //写配置文件
        {
            string xmlfile = System.Windows.Forms.Application.ExecutablePath + ".config";
            DataSet ds = new DataSet();//创建一个DataSet并建一个表 
            ds.ReadXml(xmlfile);//读取XML文件   
            ds.Tables["add"].PrimaryKey = new DataColumn[] { ds.Tables["add"].Columns["name"] };  //设置主键
            string Server = tb_server.Text.ToString();
            string Database = tb_database.Text.ToString();
            string usr = tb_user.Text.ToString();
            string psw = tb_psw.Text.ToString();
            ds.Tables["add"].Rows.Find("DbHelper")["connectionString"] = "Server="+Server+";Database="+Database+";User ID="+usr+";Password="+psw;
            ds.WriteXml(xmlfile);//将ds的更改写进xml中
            MessageBox.Show("配置保存成功!","提示");
        }
       读配置文件可以调用自带(红色标住代码)的方法。
       特别注意:要通过添加引用来加System.configration程序集,不要使用using System.configration.
          
        private void GetValue()
        {
            string conn = null;
            conn = System.Configuration.ConfigurationManager.ConnectionStrings["DbHelper"].ConnectionString;
            string[] abc = conn.Split(';');
            tb_server.Text = (abc[0].Split('='))[1].ToString();
            tb_database.Text = (abc[1].Split('='))[1].ToString();
            tb_user.Text = (abc[2].Split('='))[1].ToString();
            tb_psw.Text = (abc[3].Split('='))[1].ToString();
        }
       需要添加的引用如下:
using System.Xml;
using System.Data.SqlClient;

本文来源于Woody的鸟窝(Woody's Blog) http://www.smartgz.com, 原文地址:http://www.smartgz.com/blog/Article/1089.asp 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: