天天看點

C#讀寫ini檔案詳解

C#讀寫ini檔案之前要了解的概念:INI就是擴充名為"INI"的檔案,其實他本身是個文本檔案,可以用記事本打開,主要存放的是使用者所做的選擇或系統的各種參數.

C#讀寫ini檔案其實并不是普通的文本檔案.它有自己的結構.由若幹段落(SECTION)組成,在每個帶括号的标題下面,是若幹個以單個單詞開頭的關鍵字(KEYWORD)和一個等号,等号右邊就是關鍵字的值(VALUE).例如:

  1. [Section1]  
  2.     KeyWord1 = Value1  
  3.     KeyWord2 = Value2  
  4.     ...  
  5. [Section2]  
  6.     KeyWord3 = Value3  
  7.     KeyWord4 = Value4 

C#讀寫ini檔案最初的想法:C#命名空間中沒有直接讀寫INI的類,當然如果你把INT當成文本檔案用System.IO類來讀寫算我沒說.

我現在介紹的是系統處理INI的方法.

雖然C#中沒有,但是在"kernel32.dll"這個檔案中有Win32的API函數--WritePrivateProfileString()和GetPrivateProfileString()

C#讀寫ini檔案實作之C#聲明INI檔案的寫操作函數WritePrivateProfileString():

  1. [DllImport( "kernel32" )]  
  2.   private static extern long WritePrivateProfileString (
  3.  string section ,string key , string val   
  4. , string filePath ) ; 

參數說明:

section:INI檔案中的段落;

key:INI檔案中的關鍵字;

val:INI檔案中關鍵字的數值;

filePath:INI檔案的完整的路徑和名稱。

C#讀寫ini檔案實作之C#申明INI檔案的讀操作函數GetPrivateProfileString():

  1. [DllImport("kernel32")]  
  2.  private static extern int GetPrivateProfileString (
  3.  string section ,  
  4.   string key , string def , StringBuilder retVal ,  
  5.   int size , string filePath ) ; 

參數說明:

section:INI檔案中的段落名稱;

key:INI檔案中的關鍵字;

def:無法讀取時候時候的預設數值;

retVal:讀取數值;

size:數值的大小;

filePath:INI檔案的完整路徑和名稱。

下面是一個C#讀寫ini檔案的類:

  1. public class INIClass  
  2. {  
  3.  public string inipath;  
  4.  [DllImport("kernel32")]  
  5.  private static extern long WritePrivateProfileString(
  6. string section,string key,string val,string filePath);  
  7.  [DllImport("kernel32")]  
  8.  private static extern int GetPrivateProfileString(
  9. string section,string key,
  10. string def,StringBuilder retVal,
  11. int size,string filePath);  
  12.  /// ﹤summary﹥  
  13.  /// 構造方法  
  14.  /// ﹤/summary﹥  
  15.  /// ﹤param name="INIPath"﹥檔案路徑﹤/param﹥  
  16.  public INIClass(string INIPath)  
  17.  {  
  18.   inipath = INIPath;  
  19.  }  
  20.  /// ﹤summary﹥  
  21.  /// 寫入INI檔案  
  22.  /// ﹤/summary﹥  
  23.  /// ﹤param name="Section"﹥項目名稱(如 [TypeName] )﹤/param﹥  
  24.  /// ﹤param name="Key"﹥鍵﹤/param﹥  
  25.  /// ﹤param name="Value"﹥值﹤/param﹥  
  26.  public void IniWriteValue(string Section,string Key,string Value)  
  27.  {  
  28.   WritePrivateProfileString(Section,Key,Value,this.inipath);  
  29.  }  
  30.  /// ﹤summary﹥  
  31.  /// 讀出INI檔案  
  32.  /// ﹤/summary﹥  
  33.  /// ﹤param name="Section"﹥項目名稱(如 [TypeName] )﹤/param﹥  
  34.  /// ﹤param name="Key"﹥鍵﹤/param﹥  
  35.  public string IniReadValue(string Section,string Key)  
  36.  {  
  37.   StringBuilder temp = new StringBuilder(500);  
  38.   int i = GetPrivateProfileString(Section,Key,"",temp,500,this.inipath);  
  39.   return temp.ToString();  
  40.  }  
  41.  /// ﹤summary﹥  
  42.  /// 驗證檔案是否存在  
  43.  /// ﹤/summary﹥  
  44.  /// ﹤returns﹥布爾值﹤/returns﹥  
  45.  public bool ExistINIFile()  
  46.  {  
  47.   return File.Exists(inipath);  
  48.  }  

C#讀寫ini檔案的相關内容就向你介紹到這裡,希望對你了解和學習C#讀寫ini檔案有所幫助。

【from http://developer.51cto.com/art/200908/143715.htm】

-------------------------------------------------------------------------------------------------------------------------------------------

在作應用系統開發時,管理配置是必不可少的。例如資料庫伺服器的配置、安裝和更新配置等等。由于Xml的興起,現在的配置檔案大都是以xml文檔來存儲。比如Visual Studio.Net自身的配置檔案Mashine.config,Asp.Net的配置檔案Web.Config,包括我在介紹Remoting中提到的配置檔案,都是xml的格式。

傳統的配置檔案ini已有被xml檔案逐漸代替的趨勢,但對于簡單的配置,ini檔案還是有用武之地的。ini檔案其實就是一個文本檔案,它有固定的格式,節Section的名字用[]括起來,然後換行說明key的值:

[section]

key=value

如資料庫伺服器配置檔案:

DBServer.ini

[Server]

Name=localhost

[DB]

Name=NorthWind

[User]

Name=sa

在C#中,對配置檔案的讀寫是通過API函數來完成的,代碼很簡單:

using System;

using System.Text;

using System.IO;

using System.Runtime.InteropServices;

namespace PubOp

{

    public class OperateIniFile

    {

        #region API函數聲明

        [DllImport("kernel32")]//傳回0表示失敗,非0為成功

        private static extern long WritePrivateProfileString(string section,string key,

            string val,string filePath);

        [DllImport("kernel32")]//傳回取得字元串緩沖區的長度

        private static extern long GetPrivateProfileString(string section,string key,

            string def,StringBuilder retVal,int size,string filePath);

        #endregion

        #region 讀Ini檔案

        public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)

        {

            if(File.Exists(iniFilePath))

            {

                StringBuilder temp = new StringBuilder(1024);

                GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);

                return temp.ToString();

            }

            else

            {

                return String.Empty;

            }

        }

        #endregion

        #region 寫Ini檔案

        public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)

        {

            if(File.Exists(iniFilePath))

            {

                long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);    

                if(OpStation == 0)

                {

                    return false;

                }

                else

                {

                    return true;

                }

            }

            else

            {

                return false;

            }

        }

        #endregion

    }

}

簡單說明一下方法WriteIniData()和ReadIniData()的參數。

Section參數、Key參數和IniFilePath不用再說,Value參數表明key的值,而這裡的NoText對應API函數的def參數,它的值由使用者指定,是當在配置檔案中沒有找到具體的Value時,就用NoText的值來代替。

繼續閱讀