views:

327

answers:

1

I want to copy a part of a FileStream to a memory stream.

FileStream.Write(Pointer(MemoryStream)^, MemoryStream.Size);
FileStream.Read(Pointer(MemoryStream)^, count);

Is that right? it isn't working for me.

+2  A: 

You have to Read() from the FileStream into a separate buffer and then Write() that to the MemoryStream, ie:

var
  Buffer: PByte;

GetMem(Buffer, NumberOfBytes);
try
  FileStream.ReadBuffer(Buffer^, NumberOfBytes);
  MemoryStream.WriteBuffer(Buffer^, NumberOfBytes);
finally
  FreeMem(Buffer);
end;

Since you are dealing with two TStream objects, it would be easier to use the TStream.CopyFrom() method instead, ie:

MemoryStream.CopyFrom(FileStream, NumberOfBytes);
Remy Lebeau - TeamB
Thanks a lot! I used the CopyFrom, but I think your solutin will give me a better performance.Thanks again.
Database Designer
the TStream.CopyFrom() method uses a similar read-into-buffer-than-write-it approach internally, but does so with more error handling and buffer management than what I showed.
Remy Lebeau - TeamB
ReadBuffer should be used when the number of bytes to read is known and fixed, better to use Read - it can actually return less bytes than the buffer size when there's no more. I'd write:BytesRead := FileStream.Read(Buffer^, NumberOfBytes);MemoryStream.Write(Buffer^, BytesRead);
ldsandon
Since the OP is wanting to copy a portion of a file, presumably the OP does know ahead of time how many bytes to copy.
Remy Lebeau - TeamB