INI文件结构解释
C#读写ini文件之前要了解的概念:INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打开,主要存放的是用户所做的选择或系统的各种参数.
C#读写ini文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如:
[Section1]
KeyWord1 = Value1
KeyWord2 = Value2
...
[Section2]
KeyWord3 = Value3
KeyWord4 = Value4
本工具使用系统API处理INI的方法
"kernel32.dll"这个文件中有Win32的API函数–WritePrivateProfileString()和GetPrivateProfileString()
工具类使用以下方法进行封装
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(
string lpAppName, // points to section name
string lpKeyName, // points to key name
string lpDefault, // points to default string
byte[] lpReturnedString, // points to destination buffer
uint nSize, // size of destination buffer
string lpFileName // points to initialization filename
);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName, // pointer to section name
string lpKeyName, // pointer to key name
string lpString, // pointer to string to add
string lpFileName // pointer to initialization filename
);
以下为工具使用方法
private static INIFileHelper _file;
private static void Test()
{
string strPath = AppDomain.CurrentDomain.BaseDirectory;
//初始化文件(无需在意配置文件是否存在,在初始化时会主动进行文件创建)
_file = new INIFileHelper(strPath + "config.ini");
//表示为读取CONFIG节点下AAA字段的值(在没有取得数据时默认值为NONE)
//同理可以读取任意节点下任意字段的值
string readStr = _file.ReadString("CONFIG", "AAA", "NONE");
//表示为写入CONFIG节点下BBB字段的值(BBB字段的值为NONE)
//同理可以写入任意节点下任意字段的值
_file.WriteString("CONFIG", "BBB", "NONE");
//表示为删除CONFIG节点下CCC字段
//同理可以删除任意节点下的任意字段
_file.DeleteKey("CONFIG", "CCC");
}
工具类下载地址:INIFileHelper.cs