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的格式;

只能自己转换文件格式,转换方法如下:

            //以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);
            }

成功!

猜你喜欢

转载自www.cnblogs.com/fuhao/p/11412893.html
今日推荐