Warm tip: This article is reproduced from serverfault.com, please click

How to save a UTF-16 with BOM file with Inno Setup

发布于 2020-11-29 12:29:26

How to save a string to a text file with UTF-16 (UCS-2) encoding with BOM?

The SaveStringsToUTF8File saves as UTF-8.

Using streams saves it as ANSI.

var
  i:integer;
begin
  for i := 1 to length(aString) do begin
    Stream.write(aString[i],1);
    Stream.write(#0,1);
  end;
  stream.free;
end;
Questioner
none
Viewed
0
Martin Prikryl 2020-12-02 18:39:30

As the Unicode string (in the Unicode version of Inno Setup – the only version as of Inno Setup 6) actually uses the UTF-16 LE encoding, all you need to do is to copy the (Unicode) string to a byte array (AnsiString) bit-wise. And add the UTF-16 LE BOM (FEFF):

procedure RtlMoveMemoryFromStringToPtr(Dest: PAnsiChar; Source: string; Len: Integer);
  external 'RtlMoveMemory@kernel32.dll stdcall';
  
function SaveStringToUFT16LEFile(FileName: string; S: string): Boolean;
var
  A: AnsiString;
begin
  S := #$FEFF + S; 
  SetLength(A, Length(S) * 2);
  RtlMoveMemoryFromStringToPtr(A, S, Length(S) * 2);
  Result := SaveStringToFile(FileName, A, False);
end;

This is just an opposite of: Inno Setup Pascal Script - Reading UTF-16 file.