C# 讀取ini配置文件

雖然微軟早已經建議在WINDOWS中用註冊表代替INI文件,但是在實際應用中,INI文件仍然有用武之地,尤其現在綠色軟件的流行,越來越多的程序將自己的一些配置信息保存到了INI文件中。

  INI文件是文本文件,由若干節(section)組成,在每個帶括號的標題下面,是若干個關鍵詞(key)及其對應的值(Value):

  [Section]
  Key=Value

VC中提供了API函數進行INI文件的讀寫操作,但是微軟推出的C#編程語言中卻沒有相應的方法,下面我介紹一個讀寫INI文件的C#類並利用該類保存窗體的座標,當程序再次運行的時候,窗體將顯示在上次退出時的位置。

INIFILE類:

using System;
using System.IO;
using System.Runtime.InteropServices;

因爲我們需要調用API函數,所以必須創建System.Runtime.InteropServices命名空間以提供可用於訪問 .NET 中的 COM 對象和本機 API 的類的集合。

[c-sharp] view plaincopy
  1. using System.Text;  
  2.   
  3. namespace Ini  
  4. {  
  5.     public class IniFile  
  6.     {  
  7.         public string path;             //INI文件名  
  8.   
  9.         [DllImport("kernel32")]  
  10.         private static extern long WritePrivateProfileString(string section,string key,  
  11.                     string val,string filePath);  
  12.   
  13.         [DllImport("kernel32")]  
  14.         private static extern int GetPrivateProfileString(string section,string key,string def,  
  15.                     StringBuilder retVal,int size,string filePath);  
  16.   
  17.         //聲明讀寫INI文件的API函數  
  18.         public IniFile(string INIPath)  
  19.         {  
  20.             path = INIPath;  
  21.         }  
  22.   
  23.         //類的構造函數,傳遞INI文件名  
  24.         publicvoid IniWriteValue(string Section,string Key,string Value)  
  25.         {  
  26.             WritePrivateProfileString(Section,Key,Value,this.path);  
  27.         }  
  28.   
  29.         //寫INI文件  
  30.         publicstring IniReadValue(string Section,string Key)  
  31.         {  
  32.             StringBuilder temp = new StringBuilder(255);  
  33.             int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);  
  34.             return temp.ToString();  
  35.         }  
  36.   
  37.         //讀取INI文件指定  
  38.     }  
  39. }  

調用INIFILE類:

新建一個標準的C# WINDOWS應用程序項目,在窗體中分別增加命名爲sect、key、val的三個文本框。

增加如下代碼:

using Ini;			//創建命名空間

//當窗體關閉時保存窗體座標
[c-sharp] view plaincopy
  1. privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)  
  2. {  
  3.     IniFile ini = new IniFile("C://test.ini");  
  4.     ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString());  
  5.     ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString());  
  6.   
  7.     //ToString方法將數字轉換爲字符串  
  8. }  
//當窗體啓動時,讀取INI文件的值並賦值給窗體
[c-sharp] view plaincopy
  1. privatevoid Form1_Load(object sender, System.EventArgs e)  
  2. {  
  3.     IniFile ini = new IniFile("C://test.ini");  
  4.     Point p=new Point();  
  5.   
  6.     //判斷返回值,避免第一次運行時爲空出錯  
  7.     if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))  
  8.     {  
  9.         p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));  
  10.         p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));  
  11.   
  12.         // int.Parse將字符串轉換爲int  
  13.         this.Location =p;  
  14.     }  
  15. }  
 
==============================================
其他方法:
DllImport("kernel32.dll")]
public extern static int GetPrivateProfileString(string segName, string keyName, string sDefault, StringBuilder buffer, int nSize, string fileName);

public extern static int GetPrivateProfileStringA(string segName, string keyName, string sDefault, byte[] buffer, int iLen, string fileName); // ANSI版本

[DllImport("kernel32.dll")] public extern static int GetPrivateProfileSection(string segName, StringBuilder buffer, int nSize, string fileName);

[DllImport("kernel32.dll")] public extern static int WritePrivateProfileSection(string segName, string sValue, string fileName);

[DllImport("kernel32.dll")] public extern static int WritePrivateProfileString(string segName, string keyName, string sValue, string fileName);

[DllImport("kernel32.dll")] public extern static int GetPrivateProfileSectionNamesA(byte[] buffer, int iLen, string fileName);

 
[c-sharp] view plaincopy
  1. // 封裝的方法中,最有價值的是獲取所有Sections和所有的Keys,網上關於這個的代碼大部分是錯誤的,這裏給出一個正確的方法:  
  2. /// 返回該配置文件中所有Section名稱的集合  
  3. public ArrayList ReadSections()  
  4. {  
  5.     byte[] buffer = new byte[65535];  
  6.     int rel = 0;// GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), _FileName);  
  7.     int iCnt, iPos;  
  8.     ArrayList arrayList = new ArrayList();  
  9.     string tmp;  
  10.     if (rel > 0)  
  11.     {  
  12.         iCnt = 0; iPos = 0;  
  13.         for (iCnt = 0; iCnt < rel; iCnt++)  
  14.         {  
  15.             if (buffer[iCnt] == 0x00)  
  16.             {  
  17.                 tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();  
  18.                 iPos = iCnt + 1;  
  19.                 if (tmp != "")  
  20.                     arrayList.Add(tmp);  
  21.             }  
  22.         }  
  23.     }  
  24.     return arrayList;  
  25. }  
  26.   
  27. // 獲取節點的所有KEY值  
  28.   
  29. public ArrayList ReadKeys(string sectionName)  
  30. {  
  31.   
  32.     byte[] buffer = new byte[5120];  
  33.     int rel = 0;// GetPrivateProfileStringA(sectionName, null, "", buffer, buffer.GetUpperBound(0), _FileName);  
  34.   
  35.     int iCnt, iPos;  
  36.     ArrayList arrayList = new ArrayList();  
  37.     string tmp;  
  38.     if (rel > 0)  
  39.     {  
  40.         iCnt = 0; iPos = 0;  
  41.         for (iCnt = 0; iCnt < rel; iCnt++)  
  42.         {  
  43.             if (buffer[iCnt] == 0x00)  
  44.             {  
  45.                 tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();  
  46.                 iPos = iCnt + 1;  
  47.                 if (tmp != "")  
  48.                     arrayList.Add(tmp);  
  49.             }  
  50.         }  
  51.     }  
  52.     return arrayList;  
  53. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章