MRSNAPS
MRSNAPS

Reputation: 89

THandle of File in MemoryStream (Delphi)

I have a file loaded in a memorystream and want to get the filehandle of it without saving the file on the harddisk.

I can't figure out how to do it.

It should return the same result as CreateFile does.

  myFile:= CreateFile('myfile.exe', GENERIC_READ, FILE_SHARE_READ...

I tried it with the Memory attribute of memorystream but it doesn't return the same handle as CreateFile

  mem_stream := TMemoryStream.Create;
  mem_stream.LoadFromFile('myfile.exe');
  mem_hFile := mem_stream.Memory;
  Writeln(Format('mem_hFile: %d', [mem_hFile]));
  mem_stream.Free;

Upvotes: 0

Views: 1600

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596196

I have a file loaded in a memorystream and want to get the filehandle of it without saving the file on the harddisk.

There is no file handle in TMemoryStream. What you have done is load a copy of the file's bytes into a block of memory. The TMemoryStream.Memory property returns a pointer to that memory block.

It should return the same result as CreateFile does.

Then you have to actually call CreateFile(), either directly or indirectly, such as with a TFileStream:

fs_stream := TFileStream.Create('myfile.exe', fmOpenRead or fmShareDenyWrite);
fs_hFile := fs_stream.Handle; // <-- returns the HANDLE from CreateFile()
...
fs_stream.Free;

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612954

A memory stream has no file handle associated with it. You cannot use a memory stream with any function that expects a file handle.

Whatever your problem is, getting a file handle from a memory stream is, by dint of being impossible, not the solution.

You also seem to have a misunderstanding about the numeric values of handles. You cannot compare the numeric values of two handles and expect them to be the same value if the handles refer to the same object. Two distinct file handles have different numeric value, even if they refer to the same value.

Upvotes: 4

Related Questions