INI文件在系統配置及應用程序參數保存與設置方面,具有很重要的作用,TSVN的配置文件就是使用INI存儲的,下面我們介紹下使用C#讀寫INI文件的整體思路。
封裝WindowAPI
首先,讀寫INI文件需要用到WindowsAPI中的WritePrivateProfileString與GetPrivateProfileString方法,然而怎麼在C#中調用這兩個方法呢?
C#提供了DllImportAttribute屬性,可將該屬性應用於方法,該屬性提供對從非託管 DLL 導出的函數進行調用所必需的信息。作爲最低要求,必須提供包含入口點的 DLL 的名稱。
在此,我們需要調用包含上文提到的兩個讀寫INI文件方法的DLL(kernel32),語法如下:[DllImport("kernel32")]。
然後根據API需要的參數對兩個方法進行封裝。我們將其封裝在IniAccessor類中,封裝完畢的方法爲:
1. WritePrivateProfileString
[DllImport("kernel32")]
internal static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
參數說明:
2. GetPrivateProfileString
[DllImport("kernel32")]
internal static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder refValue, int size, string filePath);
參數說明:
注意:用 DllImport 屬性修飾的方法必須具有 extern 修飾符。
C#中調用並封裝爲IniFile類
1.寫入一個配置節
public bool IniWriteValue(string section, string key, string value)
{
if (IniAccessor.WritePrivateProfileString(section, key, value, _path) != 0)
return true;
else
return false;
}
2.讀取一個配置節
public string IniReadValue(string section, string key)
{
StringBuilder value = new StringBuilder(255);
IniAccessor.GetPrivateProfileString(section, key, null, value, 255, _path);
return value.ToString();
}
調用實例
下面的代碼是在config文件中的miscellany配置節下,添加enable-auto-props=yes屬性。
private static void EnableAutoProps()
{
string filePath = @"C:\config";
string section = "miscellany";
string key = "enable-auto-props";
IniFile iniFile = new IniFile(filePath);
iniFile.IniWriteValue(section, key, "yes");
}
其中IniFile類內封裝了讀取及寫入方法,且在初始化時,已將INI文件路徑傳入,以便後續的讀寫操作。