How to read Unicode text files #168

Question
I'd like to read text from a unicode text file, but don't know how to do this. It looks like ReadLn only works with single-byte character sets.

Not tested:

function ReadUnicodeTextFile(aFName: string): WideString;
var
  buf: array[0..1024] of WideChar;
  f: file;
  dwRest, dwRead: DWORD;
begin
  result := '';
  Assign(f, aFName);
  Reset(f, 1);
  dwRest := FileSize(f);
  Assert((dwRest mod SizeOf(widechar)) = 0); {Unicode chars always 2 bytes}
  while dwRest > 1do
  begin
    BlockRead(f, buf, sizeof(buf), dwRead);
    if dwRest > dwRead then
      Dec(dwRest, dwRead)
    else
      dwRest := 0;
    buf[dwRead mod 2] := WideChar(#0);
    result := result + PWideString(buf);
  end;
end;
Original resource: The Delphi Pool
Author: Jens Geyer
Added: 2010/06/02
Last updated: 2010/06/02