// Read an UTF8 encoded string from a stream
function LoadStringFromStream(AStream: TStream):
String;
var
ResultString: AnsiString;
StringSize: Integer;
begin
Result := '
';
if AStream.Size - AStream.Position < SizeOf(StringSize)
then
Exit;
AStream.ReadBuffer(StringSize, SizeOf(StringSize));
SetLength(ResultString, StringSize);
if AStream.Size - AStream.Position < StringSize
then
Exit;
AStream.ReadBuffer(Pointer(ResultString)^, StringSize);
{$ifdef UNICODE} // ab Delphi 2009
Result := Utf8ToString(ResultString);
{$else}
Result := Utf8Decode(ResultString);
{$endif}
end;
// Write a string to a stream and encode it to UTF8 before
procedure SaveStringToStream(AStream: TStream; AString:
String);
var
StringSize: Integer;
StringToSave: AnsiString;
begin
StringToSave := Utf8Encode(AString);
StringSize := Length(StringToSave);
AStream.WriteBuffer(StringSize, SizeOf(StringSize));
AStream.WriteBuffer(Pointer(StringToSave)^, StringSize);
end;