WinForm下App.config設定檔的讀與寫

來源:互聯網
上載者:User

      先來看下我操作的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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.