0

I'm attempting to get an array of bytes from a TMemoryStream. I'm struggling to understand how a memory stream works. To my understand I should just be able to loop through the MemoryStream using the Position and Size properties.

My expected result is to populate an array of bytes looping through the memory stream however when adjusting the Position property of the Memory stream it jumps from example 0 to 2 and then from 2 to 6.

Data.Position := 0;
repeat
   SetLength(arrBytes, Length(arrBytes) + 1);

   Data.Read(arrBytes[High(arrBytes)], Data.Size);

   Data.Position := Data.Position + 1;
until (Data.Position >= Data.Size -1);

The above code results in partial or in some cases just no data at all. How can I correctly convert the data from a memory stream to an Array of Byte

3
  • 1
    Reading moves the position in the stream. Commented Nov 12, 2022 at 12:14
  • @Brian If I take out the Data.Position := Data.Position + 1; and debug it I can see that the Position does not change but stays at 0 making a endless loop. Is there something else I am perhaps doing wrong? Commented Nov 12, 2022 at 12:39
  • 1
    Data.Read(arrBytes[High(arrBytes)], Data.Size); attempts to fit 1561563 bytes (say) in a single byte. Probably you want Data.Read(arrBytes[High(arrBytes)], 1); and no Data.Position := Data.Position + 1. But this is an extremely slow and inefficient approach. Commented Nov 12, 2022 at 18:13

1 Answer 1

2

When reading data from TMemoryStream or any other stream for that matter the position is automatically advanced by the number of bytes read.

From TMemoryStream.Read documentation

Reads up to Count bytes from the memory stream into Buffer and advances the current position of the stream by the number of bytes read.

So if you are reading data from TMemoryStream sequentially you don't have to change the memory position yourself as it is done automatically.

Sign up to request clarification or add additional context in comments.

1 Comment

This was the case but only when TBytes is used as the array. When using TArray<Byte> or array of Byte it seems the auto increment fails because no bytes are read. I always thought those 3 array types were the same but it appears not to be so. I need to do more research regarding bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.