在C#中没有提供直接操作INI文件的类,所以只能调用API函数操作
/******************************示例INI文件*************************************/
;默认首页1
[default]
url1=http://www.tiantian21.com/servicemanage/netbar/default.html
url2=http://www.tiantian21.com/servicemanage/netbar/index.html
/******************************************************************************/
;后面的视为注释
[]里面的视为关键字名称
url1,url2视为关键字所对应的值
操作INI文件的API
#region 声明读写INI文件的API函数
[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 defVal, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
#endregion
/******************************************************************************/
section:要读取的段落名
key: 要读取的键
defVal: 读取异常的情况下的缺省值
retVal: 此参数类型不是string,而是Byte[]用于返回byte类型的section组或键值组。
size: 值允许的大小
filePath: INI文件的完整路径和文件名
/******************************************************************************/
然后写两个函数用来操作INI文件的读与写:
写入(更新)INI文件:
public void IniWriteValue(string section, string key, string iValue)
{
WritePrivateProfileString(section, key, iValue, Path);
}
读出INI文件的数据(返回字符串):
public string IniReadValue(string section, string key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(section, key, "", temp, 255, Path);
return temp.ToString();
}
读出INI文件的数据(返回字节数组):
public byte[] IniReadValues(string section, string key)
{
byte[] temp = new byte[255];
int i = GetPrivateProfileString(section, key, "", temp,255, Path);
return temp;
}
/******************************************************************************/
section就是default
key就是url1,url2
iValue就是url1,url2 对应的值(当key=null时,获取所有)
/******************************************************************************/
其中读取的时候涉及到有时要把所有的段落名全读出来,就要使用字节数组读取,
例如:
byte[] allSection = IniReadValues(null, null); //获取所有的段落标志
ASCIIEncoding ascii = new ASCIIEncoding();
string[] keyName = ascii.GetString(allSection).Split(new char[1] { '\0' });//转换过来放在数组里
删除:
//删除ini文件下default段落下的所有键
IniWriteValue("default", null, null);
//删除ini文件下所有段落
IniWriteValue(null, null, null);
增加新的节点
IniWriteValue("新节点的名称(不能重复)", "关键字名称", "关键字对应的值");
更新其实就是增加,只要保证节点名称一样:
IniWriteValue("原节点的名称(必须是存在的,否则就会新建一个)", "关键字名称", "关键字对应的值");