Discussion:
TMemoryStream and TFileStream in Delphi
(too old to reply)
Tariq
2006-03-20 12:41:23 UTC
Permalink
I have a situation where I convert (using the function shown below) any
binary file to an OleVariant and then send it to a DCOM Server which
converts it back to a FileStream and saves it to a disk.

On the client computer if I load a file into a TFileStream then every
thing works fine. However in some siutations I have a file loaded in a
TMemoryStream. If I convert the content of TMemoryStream in to an
OleVariable and send it to COM server, it saves an EMPTY file on the
disk. It seems as if the binary content in the TFileStream is not
handled the same way as it is handled in TMemoryStream.

I want some suggestion as to
(1) How can I safely copy the content of TMemoryStream to a TFileStream
or
(2) Convert the Content of TMemoryStream to an OleVariant.

Here is the function that I use to convert a FileStream to OleVariant:

function StreamToOleVariant(Stream: TStream; Count: integer):
OleVariant;
var pBuf: Pointer;
begin
Result :=VarArrayCreate([0, Count-1], varByte);
pBuf := VarArrayLock(Result);
Stream.Read(TByteArray(pBuf^), Length(TByteArray(Result)));
VarArrayUnlock(Result);
end;
Rob Kennedy
2006-03-20 16:18:20 UTC
Permalink
Post by Tariq
I have a situation where I convert (using the function shown below) any
binary file to an OleVariant and then send it to a DCOM Server which
converts it back to a FileStream and saves it to a disk.
On the client computer if I load a file into a TFileStream then every
thing works fine. However in some siutations I have a file loaded in a
TMemoryStream. If I convert the content of TMemoryStream in to an
OleVariable and send it to COM server, it saves an EMPTY file on the
disk. It seems as if the binary content in the TFileStream is not
handled the same way as it is handled in TMemoryStream.
When you create a TFileStream, its Position property is 0 and the stream
has data in it. When you create a TMemoryStream, its position is 0, but
the stream is empty. Afer you fill the stream by calling Write, the
Position property is at the end of the stream. The Read method always
reads from the current Position. If you want to read from the beginning
of the stream, set Position back to zero.
Post by Tariq
OleVariant;
var pBuf: Pointer;
begin
Result :=VarArrayCreate([0, Count-1], varByte);
pBuf := VarArrayLock(Result);
Stream.Read(TByteArray(pBuf^), Length(TByteArray(Result)));
I'm not sure what those type casts are for. Since the first parameter
for Read is an untyped var parameter, you don't need to type-cast pBuf^
to anything. You already know the length of the array. It's Count.
There's no need to compute it with the Length function, especially when
Result isn't a TByteArray anyway.
Post by Tariq
VarArrayUnlock(Result);
end;
--
Rob
Loading...