C# UTF-8文件带BOM和不带BOM文件的转换

读取INI文件使用的是GetPrivateProfileString方法,本身读写ini文件没有问题。

调用C++的API对同一个ini文件进行处理后,发现首个Section的值读不出来;发现是API更改了ini文件格式。

本来C#进行读写的ini文件是UTF-8不带BOM的格式,C++ API写值后将ini文件格式改成UTF-8带BOM。

API那边没有办法更改,GetPrivateProfileString我也不知道该怎么设定成带BOM的格式;

只能本身转换文件格式,转换方法以下:spa

//以UTF-8带BOM格式读取文件内容
            Encoding end = new UTF8Encoding(true); string str = string.Empty; using (StreamReader sr = new StreamReader(ini.Path, end)) { str = sr.ReadToEnd(); } //以UTF-8不带BOM格式从新写入文件
            end = new UTF8Encoding(false); using (StreamWriter sw = new StreamWriter(ini.Path, false, end)) { sw.Write(str); }

成功!code

相关文章
相关标签/搜索