Search code examples
delphidelphi-7

Delphi: Copy FileStream to MemoryStream


I want to copy a part of a FileStream to a MemoryStream.

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

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


Solution

  • 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);