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

相關文章
相關標籤/搜索