C#本身沒有提供訪問INI配置文件的方法,但是我們可以使用WinAPI提供的方法來處理INI文件的讀寫,代碼很簡單!網上有大量現成的代碼,這裡只是作為記錄和整理,方便日後使用。
INI配置文件的組成?
INI文件是文本文件,由若干節(section)組成,在每個帶中括號的節名稱下,是若干個關鍵詞(key)及其對應的值(Value),這些關鍵詞(key)屬於位於關鍵詞(key)上的節(section)。
[Section]
Key1=Value1
Key2=Value2
Windows系統自帶的Win32的API函數GetPrivateProfileString()和WritePrivateProfileString()分別實現了對INI文件的讀寫操作
所以可以寫一個簡單的類來讀寫ini文件,以滿足一般應用的配置存取需求:
示例
class
IniFile
{
/*
* 聲明API函數
*/
public
string
iniPath;
[DllImport(
"kernel32"
)]
private
static
extern
long
WritePrivateProfileString(
string
section,
string
key,
string
val,
string
filePath);
[DllImport(
"kernel32"
)]
private
static
extern
int
GetPrivateProfileString(
string
section,
string
key,
string
def, StringBuilder retVal,
int
size,
string
filePath);
/// <summary>
/// 構造函數
/// </summary>
/// <param name="iniPath">ini文件路徑,默認為當前路徑下default.ini</param>
public
IniFile(
string
iniPath =
"./default.ini"
)
{
this
.iniPath = iniPath;
}
/// <summary>
/// 寫入ini文件
/// </summary>
/// <param name="Section">Section</param>
/// <param name="Key">鍵</param>
/// <param name="Value">值</param>
public
void
writeIni(
string
Section,
string
Key,
string
Value)
{
WritePrivateProfileString(Section, Key, Value,
this
.iniPath);
}
/// <summary>
/// 寫入ini文件,不管section,默認放在default裡
/// </summary>
/// <param name="Key">鍵</param>
/// <param name="Value">值</param>
public
void
writeIni(
string
Key,
string
Value)
{
WritePrivateProfileString(
"default"
, Key, Value,
this
.iniPath);
}
/// <summary>
/// 讀取ini文件
/// </summary>
/// <param name="Section">Section</param>
/// <param name="Key">鍵</param>
/// <returns>返回的值</returns>
public
string
readIni(
string
Section,
string
Key)
{
StringBuilder temp =
new
StringBuilder(256);
int
i = GetPrivateProfileString(Section, Key,
""
, temp, 256,
this
.iniPath);
return
temp.ToString();
}
/// <summary>
/// 讀取section,不管section,默認從default裡讀取
/// </summary>
/// <param name="Key">鍵</param>
/// <returns>返回值</returns>
public
string
readIni(
string
Key)
{
return
readIni(
"default"
, Key);
}
/// <summary>
/// 查詢ini文件是否存在
/// </summary>
/// <returns>是否存在</returns>
public
bool
existINIFile()
{
return
File.Exists(iniPath);
}
}
調用方式:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17class
Program
{
static
void
Main(
string
[] args)
{
IniFile iniFile =
new
IniFile(
"./hello.ini"
);
iniFile.writeIni(
"section1"
,
"key1"
,
"value11"
);
iniFile.writeIni(
"section1"
,
"key2"
,
"value12"
);
iniFile.writeIni(
"section2"
,
"key1"
,
"value21"
);
iniFile.writeIni(
"section2"
,
"key2"
,
"value22"
);
iniFile.writeIni(
"key"
,
"value"
);
string
str = iniFile.readIni(
"key"
);
Console.WriteLine(str);
Console.ReadKey();
}
}