-1

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.

Mohamad
  • 1,089
  • 4
  • 19
  • 37
  • When you step through the code in the debugger what line does the exception happen on? – Keith Miller May 03 '15 at 08:42
  • Last line : stream.ReadBuffer(Result[1], nChars * SizeOf(Result[1])); – Mohamad May 03 '15 at 08:44
  • 2
    Please note, that you are supposed to mention [`the source`](http://stackoverflow.com/a/1354120/960757) from where did you get this code so we could optionally fix it there (but not only because of that). Or just drop a comment to the post author. In this case simply read the post to the end. – TLama May 03 '15 at 08:55
  • This [code](http://stackoverflow.com/questions/1354092/widestring-storing-in-tfilestream-delphi-7-what-is-the-fastest-way/1354120#1354120) will not work, I tried it before. – Mohamad May 03 '15 at 09:02

1 Answers1

2

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490