Search code examples
delphiwinapidelphi-xe8

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;

Solution

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