在做應用系統開發時,管理配置是必不可少的。例如資料庫伺服器的配置、安裝和更新配置等等。由於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函數來完成的,代碼很簡單:
INI設定檔操作類
public class IniTool
{
#region ---API函式宣告---
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key,
string value, 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 defValue,string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder str = new StringBuilder(1024);
GetPrivateProfileString(section, key, defValue, str, 1024, iniFilePath);
return str.ToString();
}
else
{
return string.Empty;
}
}
public static bool WriteIniData(string section, string key, string value, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
long result = WritePrivateProfileString(section, key, value, iniFilePath);
return result == 0 ? false : true;
}
return false;
}
#endregion
}
簡單說明以下方法WriteIniData()和ReadIniData()的參數。
Section參數、Key參數和IniFilePath不用再說,Value參數表明key的值,而這裡的NoText對應API函數的def參數,它的值由使用者指定,是當在設定檔中沒有找到具體的Value時,就用NoText的值來代替。
出處:http://kb.cnblogs.com/page/43446/