前提1
ini文件是windows系统配置文件,所以只在windows程序使用改类型配置文件(不讨论其他平台加载该文件)
前提2
字符集,中英文:遵照文本保存是什么格式,读取就按什么格式读取
统一utf-8
问题
部分电脑记事本打开ini会自动保存成带BOM格式的文件。带BOM会导致读取无效
//判断是否是带utf-8 BOM格式的 前三个字节0xef 0xbb 0xbf
//剔除前三个字节头即可
public string GetContentWithoutBOM(byte[] buffer)
{
if (buffer != null)
{
if (buffer.Length <= 3)//当作不带bom
{
return Encoding.UTF8.GetString(buffer);
}
else
{
//带bom
if (buffer[0] == 0xef
&& buffer[1] == 0xbb
&& buffer[2] == 0xbf)
{
//剔除前三个BOM格式字节,剩余数据为正常数据
byte[] newBuffer = new byte[buffer.Length - 3];
for (int i = 0; i < newBuffer.Length; i++)
{
newBuffer[i] = buffer[i + 3];
}
return Encoding.UTF8.GetString(newBuffer);//重新保存为不带bom的ini文件
}
else
{
return Encoding.UTF8.GetString(buffer);
}
}
}
return string.Empty;
}
读写
#region ini win32API读取
//声明读写INI文件的API函数
[DllImport("kernel32")]
public static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
/// <summary>
/// 读取ini文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="Section">节 名称</param>
/// <param name="Ident">key值</param>
/// <param name="Default">读取失败返回值</param>
/// <returns></returns>
public static string ReadIniString(string filePath, string Section, string Ident, string Default)
{
byte[] Buffer = new byte[65535];
int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.Length, filePath);
string s = Encoding.UTF8.GetString(Buffer, 0, bufLen);
return s.Trim();
}
/// <summary>
/// 写入ini文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="Section">节 名称</param>
/// <param name="Ident">key值</param>
/// <param name="Value">value写入值</param>
/// <returns></returns>
public static bool WriteIniString(string filePath, string Section, string Ident, string Value)
{
bool bResult = WritePrivateProfileString(Section, Ident, Value, filePath);
return bResult;
}
#endregion