Create a UTF8 file without BOM with Inno Setup (Unicode version)

后端 未结 1 342
长情又很酷
长情又很酷 2020-12-20 03:17

I have to read and modify some JSON files. The file encoding must be UTF8 without BOM or the JSON file will be not accepted.

I tried the following Code:



        
相关标签:
1条回答
  • 2020-12-20 04:05

    Use the WideCharToMultiByte function to convert the string to UTF-8 and just save it:

    const
      CP_UTF8 = 65001;
    
    function WideCharToMultiByte(CodePage: UINT; dwFlags: DWORD;
      lpWideCharStr: string; cchWideChar: Integer; lpMultiByteStr: AnsiString;
      cchMultiByte: Integer; lpDefaultCharFake: Integer;
      lpUsedDefaultCharFake: Integer): Integer;
      external 'WideCharToMultiByte@kernel32.dll stdcall';
    
    function GetStringAsUtf8(S: string): AnsiString;
    var
      Len: Integer;
    begin
      Len := WideCharToMultiByte(CP_UTF8, 0, S, Length(S), Result, 0, 0, 0);
      SetLength(Result, Len);
      WideCharToMultiByte(CP_UTF8, 0, S, Length(S), Result, Len, 0, 0);
    end;
    
    function SaveStringToUTF8FileWithoutBOM(FileName: string; S: string): Boolean;
    var
      Utf8: AnsiString;
    begin
      Utf8 := GetStringAsUtf8(S);
      Result := SaveStringToFile(FileName, Utf8, False);
    end;
    

    You have to use Unicode version of Inno Setup (the only version as of Inno Setup 6).


    See also:

    • LoadStringFromFileInCP and LoadStringsFromFileInCP functions in:
      Inno Setup - Convert array of string to Unicode and back to ANSI
    • Inno Setup replace a string in a UTF-8 file without BOM
    0 讨论(0)
提交回复
热议问题