INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下:
[Section1]
key 1 = value2
key 1 = value2
……
[Section2]
key 1 = value1
key 2 = value2
……
文件由若干个段落(section)组成,每个段落又分成若干个键(key)和值(value)。Windows系统自带的Win32的API函数GetPrivateProfileString()和WritePrivateProfileString()分别实现了对INI文件的读写操作,他们位于kernel32.dll下。
读操作:
[DllImport("kernel32")]
private static extern int GetPrivateProfileString
(
string section, // section:要读取的段落名
string key, // key: 要读取的键
string defValue, // defValue: 读取异常的情况下的缺省值
StringBuilder retValue, // retValue: key所对应的值,如果该key不存在则返回空值
int size, // size: 值允许的大小
string path // path: INI文件的完整路径和文件名
);
写操作:
[DllImport("kernel32")]
private static extern long WritePrivateProfileString
(
string section, // section: 要写入的段落名
string key, // key: 要写入的键,如果该key存在则覆盖写入
string value, // value: key所对应的值
string pat