小菜的系統框架界面設計-應用程序中使用配置檔

使用背景

最近寫一個打標的配置文件讀取,讓客戶可以更改配置檔的功能,我考慮用了INI檔或修改App.config。node

概述

INI檔

INI就是擴展名爲"INI"的文件,其實他自己是個文本文件,能夠用記事本打工,主要存放的是用戶所作的選擇或系統的各類參數.
INI文件其實並非普通的文本文件.它有本身的結構.由若干段落(SECTION)組成,在每一個帶括號的標題下面,是若干個以單個單詞開頭的關鍵字(KEYWORD)和一個等號,等號右邊就是關鍵字的值(VALUE).例如:
[Section1]
    KeyWord1 = Value1
    KeyWord2 = Value2
    ...
[Section2]
    KeyWord3 = Value3
    KeyWord4 = Value4架構

C#命名空間中沒有直接讀寫INI的類,固然若是你把INT當成文本文件用System.IO類來讀寫算我沒說.
我如今介紹的是系統處理INI的方法.
雖然C#中沒有,可是在"kernel32.dll"這個文件中有Win32的API函數--WritePrivateProfileString()和GetPrivateProfileString()
C#聲明INI文件的寫操做函數WritePrivateProfileString():
[DllImport( "kernel32" )]
  private static extern long WritePrivateProfileString ( string section ,string key , string val
, string filePath ) ;
參數說明:section:INI文件中的段落;key:INI文件中的關鍵字;val:INI文件中關鍵字的數值;filePath:INI文件的完整的路徑和名稱。
C#申明INI文件的讀操做函數GetPrivateProfileString(): [DllImport("kernel32")]
private static extern int GetPrivateProfileString ( string section ,
  string key , string def , StringBuilder retVal ,
  int size , string filePath ) ;參數說明:section:INI文件中的段落名稱;key:INI文件中的關鍵字;def:沒法讀取時候時候的缺省數值;retVal:讀取數值;size:數值的大小;filePath:INI文件的完整路徑和名稱。 app

代碼實例(INI)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace IniConfigDemo
{
    public partial class Form1 : Form
    {
        public string FilePath;
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FilePath = Application.StartupPath + "/FTPServer.ini";
            txtFilePath.Text = FilePath;

            richTextBox1.AppendText("Server:"+IniReadValue("ServerConfig","IP")+"\n");
            richTextBox1.AppendText("UserId:"+IniReadValue("ServerConfig", "UserId")+"\n");
            richTextBox1.AppendText("Password:"+IniReadValue("ServerConfig", "Password")+"\n");
        }

        private void btnCreateIni_Click(object sender, EventArgs e)
        {
            if (ExistIniFile())
            {
                if (MessageBox.Show(@"已存在一外同名文件,是否要覆蓋此文件?", @"警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    CreateIniFile();
                }
            }
            else
            {
                CreateIniFile();
            }
         
        }
        void CreateIniFile()
        {
            IniWriteValue("ServerConfig", "IP", "192.168.0.152");
            IniWriteValue("ServerConfig", "UserId", "aganqin");
            IniWriteValue("ServerConfig", "Password", "12345");
        }

        /// <summary>
        /// 寫入INI文件
        /// </summary>
        /// <param name="section">項目名稱(如 [TypeName] )</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void IniWriteValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, this.FilePath);
        }


        /// <summary>
        /// 讀出INI文件
        /// </summary>
        /// <param name="section">項目名稱(如 [TypeName] )</param>
        /// <param name="key"></param>
        public string IniReadValue(string section, string key)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(section, key, "", temp, 500, this.FilePath);
            return temp.ToString();
        }

        /// <summary>
        /// 驗證文件是否存在
        /// </summary>
        /// <returns>布爾值</returns>
        public bool ExistIniFile()
        {
            return File.Exists(FilePath);
        }
    }
}

App.config檔

  • 應用程序配置文件是標準的 XML 文件,XML 標記和屬性是區分大小寫的。它是能夠按須要更改的,開發人員可使用配置文件來更改設置,而沒必要重編譯應用程序。配置文件的根節點是configuration。咱們常常訪問的是appSettings,它是由.Net預約義配置節。咱們常常使用的配置文件的架構是象下面的形式。先大概有個印象,經過後面的實例會有一個比較清楚的認識。下面的「配置節」能夠理解爲進行配置一個XML的節點。

    常見配置文件模式:
 
 
 
 
 
<configuration>
 <configSections> //配置節聲明區域,包含配置節和命名空間聲明 <section> //配置節聲明   <sectionGroup> //定義配置節組   
 <section> //配置節組中的配置節聲明 
 </section>
</sectionGroup> 
<appSettings> //預約義配置節
 <Custom element for configuration section> //配置節設置區域 
</appSettings> 
</configuration>

  • 只有appSettings節的配置文件及訪問方法
<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<appSettings> 
<add key="connectionstring" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" /> 
<add key="TemplatePATH" value="Template" /> 
</appSettings> 
</configuration>

代碼實例(App.config)

配置文件的方法:
string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];
使用ConfigurationSettings類的靜態屬性AppSettings就能夠直接方法配置文件中的配置信息。這個屬性的類型是NameValueCollection。 
更改配置檔的方法:
 
public static void UpdateConfig(string appKey, string Xvalue)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(AppConfig());
            XmlNode node = doc.SelectSingleNode(@"//appSettings");
            XmlElement ele = (XmlElement)node.SelectSingleNode("//add[@key='" + appKey + "']");
            ele.SetAttribute("value", Xvalue);
            doc.Save(AppConfig());
        }

總結

由於應用程序有不少配置,參數都須要用到的這些配置知識,有的須要用App.config,有的要用Ini,這須要根據需求和客戶要求來決定,也不能肯定哪種方式爲最好。ide

相關文章
相關標籤/搜索