Adriaan
Adriaan

Reputation: 806

TMemoryStream to array of bytes

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

Upvotes: 0

Views: 1124

Answers (1)

SilverWarior
SilverWarior

Reputation: 8331

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.

Upvotes: 2

Related Questions