C# 操作INI配置檔案
重構YH是遇到這個一樣問題,就是YH前臺頁面的按鈕要求實現客戶自定義,客戶可以跟隨自己的喜好安排每個按鈕的功能,所以,在每一次客戶登陸是就需要初始化客戶自定義排版,這裡就需要用到初始化檔案——INI。
.ini 檔案是Initialization File的縮寫,即初始化檔案。是windows的系統配置檔案所採用的儲存格式,統管windows的各項配置,一般使用者就用windows提供的各項圖形化管理介面就可實現相同的配置了,但在某些情況,還是要直接編輯.ini才方便,一般只有很熟悉windows才能去直接編輯。開始時用於WIN3X下面,WIN95用登錄檔代替,以及後面的內容表示一個節,相當於登錄檔中的鍵。
除了windows現在很多其他作業系統下面的應用軟體也有.ini檔案,用來配置應用軟體以實現不同使用者的要求。一般不用直接編輯這些.ini檔案,應用程式的圖形介面即可操作以實現相同的功能。它可以用來存放軟體資訊,登錄檔資訊等。
INI檔案由節、鍵、值組成。
節
[section]
引數(鍵=值)
name=value
既然ini檔案在初始化中使用,那麼免不了的需要對它進行一些寫入讀取修改的操作,當然,這些東西window已經幫我們封裝好了,我們只需要呼叫就可以了。很easy。
Ini使用到的一些API函式:
- #region 呼叫windowsAPI
- //用來讀取INI 檔案的內容
- [DllImport("Kernel32.dll")]
- private static extern int GetPrivateProfileString(string strAppName,string strKeyName,string strDefault,StringBuilder sbReturnString,int nSize,string strFileName);
- //返回所讀取的字串值的真實長度
- [DllImport("Kernel32.dll")]
- private extern static int GetPrivateProfileStringA(string strAppName, string strKeyName, string sDefault, byte[] buffer, int nSize, string strFileName);
- [DllImport("Kernel32.dll")]
- private static extern int GetPrivateProfileInt(string strAppName, string strKeyName, int nDefault, string strFileName);
- //獲取ini檔案所有的section
- [DllImport("Kernel32.dll")]
- private extern static int GetPrivateProfileSectionNamesA(byte[] buffer, int iLen, string fileName);
- //獲取指定Section的key和value
- [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
- private static extern int GetPrivateProfileSection(string lpAppName,byte[] lpReturnedString, int nSize,string lpFileName);
- //根據傳入引數的不同進行寫入或修改或刪除操作(返回值 Long,非零表示成功,零表示失敗)
- [DllImport("Kernel32.dll")]
- public static extern long WritePrivateProfileString(string strAppName, string strKeyName, string strKeyValue, string strFileName);
- //新增一個section內容列表
- [DllImport("Kernel32.dll")]
- public static extern long WritePrivateProfileSection(string strAppName, string strkeyandvalue, string strFileName);
- #endregion
呼叫這些函式的所用到的方法:
- #region 供UI呼叫的方法
- /// <summary>
- /// 判斷該ini檔案是否存在如果不存在新建一個該檔案
- /// </summary>
- public void FileExists()
- {
- try
- {
- if (!File.Exists(this.filePath))
- {
- using (FileStream fs = File.Create(this.filePath))
- {
- fs.Close();
- }
- }
- }
- catch(Exception e)
- {
- }
- }
- /// <summary>
- /// 返回該配置檔案中所有Section名稱的集合
- /// </summary>
- /// <returns></returns>
- public ArrayList ReadSections()
- {
- byte[] buffer = new byte[65535];
- int rel = GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), this.filePath);
- int iCnt, iPos;
- ArrayList arrayList = new ArrayList();
- string tmp;
- if (rel > 0)
- {
- iCnt = 0; iPos = 0;
- for (iCnt = 0; iCnt <rel; iCnt++)
- {
- if (buffer[iCnt] == 0x00)
- {
- tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
- iPos = iCnt + 1;
- if (tmp != "")
- arrayList.Add(tmp);
- }
- }
- }
- return arrayList;
- }
- /// <summary>
- /// 獲取指定節點的所有KEY的名稱
- /// </summary>
- /// <paramname="sectionName"></param>
- /// <returns></returns>
- public ArrayList ReadKeys(string sectionName)
- {
- byte[] buffer = new byte[5120];
- int rel = GetPrivateProfileStringA(sectionName, null, "", buffer, buffer.GetUpperBound(0), this.filePath);
- int iCnt, iPos;
- ArrayList arrayList = new ArrayList();
- string tmp;
- if (rel > 0)
- {
- iCnt = 0; iPos = 0;
- for (iCnt = 0; iCnt <rel; iCnt++)
- {
- if (buffer[iCnt] == 0x00)
- {
- tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
- iPos = iCnt + 1;
- if (tmp != "")
- arrayList.Add(tmp);
- }
- }
- }
- return arrayList;
- }
- /// <summary>
- /// 讀取指定節點下的指定key的value返回string
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="key">param>
- /// <returns></returns>
- public string GetIniKeyValueForStr(string section, string key)
- {
- if (section.Trim().Length <= 0 || key.Trim().Length <= 0) return string.Empty;
- StringBuilder strTemp = new StringBuilder(256);
- GetPrivateProfileString(section, key, string.Empty, strTemp, 256, this.filePath);
- return strTemp.ToString().Trim();
- }
- /// <summary>
- /// 從指定的節點中獲取一個整數值( Long,找到的key的值;如指定的key未找到,就返回預設值。如找到的數字不是一個合法的整數,函式會返回其中合法的一部分。如,對於“xyz=55zz”這個條目,函式返回55。)
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="key"></param>
- /// <returns></returns>
- public int GetIniKeyValueForInt(string section, string key)
- {
- if (section.Trim().Length <= 0 || key.Trim().Length <= 0) return 0;
- return GetPrivateProfileInt(section, key, 0, this.filePath);
- }
- /// <summary>
- /// 讀取指定節點下的所有key 和value
- /// </summary>
- /// <paramname="section"></param>
- /// <returns></returns>
- public ArrayList GetIniSectionValue(string section)
- {
- byte[] buffer = new byte[5120];
- int rel = GetPrivateProfileSection(section, buffer, buffer.GetUpperBound(0), this.filePath);
- int iCnt, iPos;
- ArrayList arrayList = new ArrayList();
- string tmp;
- if (rel > 0)
- {
- iCnt = 0; iPos = 0;
- for (iCnt = 0; iCnt <rel; iCnt++)
- {
- if (buffer[iCnt] == 0x00)
- {
- tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
- iPos = iCnt + 1;
- if (tmp != "")
- arrayList.Add(tmp);
- }
- }
- }
- return arrayList;
- }
- /// <summary>
- /// 往指定section的key中寫入value
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="key"></param>
- /// <paramname="value"></param>
- /// <returns></returns>
- public bool WriteIniKey(string section, string key, string value)
- {
- try
- {
- if (section.Trim().Length <= 0 || key.Trim().Length <= 0 || value.Trim().Length <= 0)
- {
- flag = false;
- }
- else
- {
- if (WritePrivateProfileString(section, key, value, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- /// <summary>
- /// 修改指定section的key的值
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="key"></param>
- /// <paramname="value"></param>
- /// <returns></returns>
- public bool EditIniKey(string section, string key, string value)
- {
- try
- {
- if (section.Trim().Length <= 0 || key.Trim().Length <= 0 || value.Trim().Length <= 0)
- {
- flag = false;
- }
- else
- {
- if (WritePrivateProfileString(section, key, value, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- /// <summary>
- /// 刪除指定section的指定key
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="key"></param>
- /// <returns></returns>
- public bool DeleteIniKey(string section, string key)
- {
- try
- {
- if (section.Trim().Length <= 0 || key.Trim().Length <= 0)
- {
- flag = false;
- }
- else
- {
- if (WritePrivateProfileString(section, key, null, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- /// <summary>
- /// 刪除指定section
- /// </summary>
- /// <paramname="section"></param>
- /// <returns></returns>
- public bool DeleteIniSection(string section)
- {
- try
- {
- if (section.Trim().Length <= 0)
- {
- flag = false;
- }
- else
- {
- if (WritePrivateProfileString(section, null, null, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- /// <summary>
- /// 給一個節點寫入key和value列表
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="ht"></param>
- /// <returns></returns>
- public bool WriteIniSectionAndValue(string section, Hashtable ht)
- {
- string lpString = "";
- try
- {
- if (section.Trim().Length <= 0 || ht.Count == 0)
- {
- flag = false;
- }
- else
- {
- foreach (DictionaryEntry de in ht)
- {
- lpString += de.Key+"="+de.Value;
- lpString += "\r\n";
- }
- if (WritePrivateProfileSection(section, lpString, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- /// <summary>
- /// 給一個節點寫入key 列表
- /// </summary>
- /// <paramname="section"></param>
- /// <paramname="lstKeyValue"></param>
- /// <returns></returns>
- public bool WriteIniSectionName(string section, List<string> lstKeyValue)
- {
- string lpString = "";
- try
- {
- if (section.Trim().Length <= 0 || lstKeyValue.Count == 0)
- {
- flag = false;
- }
- else
- {
- for (int i = 0; i <lstKeyValue.Count; ++i)
- {
- lpString += lstKeyValue[i];
- lpString += "\r\n";
- }
- if (WritePrivateProfileSection(section, lpString, this.filePath) == 0)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
- }
- catch
- {
- flag = false;
- }
- return flag;
- }
- #endregion
在U層,我們需要
- //建立一個INIFile物件,引數為檔案路徑
- ManagerConfigIni iniConfig = new ManagerConfigIni(AppDomain.CurrentDomain.BaseDirectory + @"\配置.ini");
然後通過相應的事件,來呼叫對應的方法即可。
如果 ini 中沒有指定的 Section,API會新建 Section,如果沒有指定的 Key則新建一個 Key 並寫入資料,如果已經存在,則用字串代替原來的值。當指定的 ini也不存在的時候,API 會自動建立一個新的檔案,所以使用 ini的好處是我們不必為了儲存少量的資料涉及到檔案操作,就連查詢檔案是否存在的操作都不必要。
使用要點:在我們實際使用的時候,用的最多的是 GetPrivateProfileString和 WritePrivateProfileString,但在對自定義 ini檔案操作的時候要注意的是,如果 lpFileName 指定的檔案沒有路徑的話,Api會去 Windows 的安裝目錄去找而不會在當前目錄找,但是每次用到 ini函式要獲取當前路徑顯然太麻煩了,這裡有一個變通的辦法,你只要在 ini 檔名前面加上 .\ 就可以了,比如說要對本目錄下的 user.ini操作,那麼檔名就是 '.\user.ini' 這樣顯然比較方便。另外,當你要把一個 Key清除的時候,可以使用把 lpString 指向一個空的字串然後使用 WritePrivateProfileString。當你要把一個 section的全部內容清空的時候,也不必把 key 一個個的清除,可以使用把 lpString指向一個空的字串然後使用 WritePrivateProfileSection。 INI檔案就是副檔名為“ini”的檔案。在Windows系統中,INI檔案是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。該檔案主要存放使用者所做的選擇以及系統的各種引數。使用者可以通過修改INI檔案,來改變應用程式和系統的很多配置。但自從Windows 95的退出,在Windows系統中引入了登錄檔的概念,INI檔案在Windows系統的地位就開始不斷下滑,這是因為登錄檔的獨特優點,使應用程式和系統都把許多引數和初始化資訊放進了登錄檔中。
http://blog.csdn.net/laner0515/article/details/8439933