Search code examples
delphidelphi-7

Convert TMemoryStream to WideString in Delphi 7


When I use this code and function in Delphi 7 an error message will be displayed :

This code convert MemoryStream content to WideString

function ReadWideString(stream: TStream): WideString;
var
  nChars: LongInt;
begin
  stream.Position := 0;
  stream.ReadBuffer(nChars, SizeOf(nChars));
  SetLength(Result, nChars);
  if nChars > 0 then
    stream.ReadBuffer(Result[1], nChars * SizeOf(Result[1]));
end;


procedure TForm1.Button2Click(Sender: TObject);
var
  mem: TMemoryStream;
begin
  mem := TMemoryStream.Create;
  mem.LoadFromFile('C:\Users\User1\Desktop\wide.txt');
  Memo1.Lines.Add(ReadWideString(mem));
end;

enter image description here

Any help would be greatly appreciated.


Solution

  • Your code works fine as is. The problem is that the input that you pass to your function is not in the expected format.

    The function that you are using expects a 4 byte integer containing the length, followed by the UTF-16 payload.

    It looks like you actually have straight UTF-16 text, without the length prepended. Read that like this:

    stream.Position := 0;
    nChars := stream.Size div SizeOf(Result[1]);
    SetLength(Result, nChars);
    if nChars > 0 then
      stream.ReadBuffer(Result[1], nChars * SizeOf(Result[1]));
    

    Now, your input may contain a UTF-16 BOM. If so you'll need to decide how to handle that.

    The bottom line here is that you need your code to match the input you provide.