ini文件加载

前提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
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值