Como salvar um UTF-16 com arquivo BOM com Inno Setup

Nov 29 2020

Como salvar uma string em um arquivo de texto com codificação UTF-16 (UCS-2) com BOM?

O SaveStringsToUTF8Filesalva como UTF-8.

Usar streams salva como 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;

Respostas

2 MartinPrikryl Nov 30 2020 at 15:12

Como o Unicode string(na versão Unicode do Inno Setup - a única versão do Inno Setup 6) realmente usa a codificação UTF-16 LE, tudo que você precisa fazer é copiar o (Unicode) stringpara um array de bytes ( AnsiString) bit- sensato. E adicione o UTF-16 LE BOM ( FEFF):

procedure RtlMoveMemoryFromStringToPtr(Dest: PAnsiChar; Source: string; Len: Integer);
  external '[email protected] 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;

Isso é exatamente o oposto de: Inno Setup Pascal Script - Lendo arquivo UTF-16 .