Delphi - MemoryStream or FileStream

I download an EXE file from the Internet using Indy (idHTTP), and I can use memystream or filestream to save it to disk, but I really don’t know if there is a difference between them (maybe in the structure of the result file?). I could not find the answer to this question.

Here, where are two simple functions to simulate what I am doing:

Function DownloadMS(FUrl, Dest: String): Boolean; var Http: TIdHTTP; Strm: TMemoryStream; Begin Result := False; Http := TIdHTTP.Create; Strm := TMemoryStream.Create; With Http, Strm Do Try Try Get(FUrl, Strm); If (Size > 0) Then Begin Position := 0; SaveToFile(Dest); Result := True; end; Except end; Finally Strm.Free; Http.Free; end; end; Function DownloadFS(FUrl, Dest: String): Boolean; var Http: TIdHTTP; Strm: TFileStream; Begin Result := False; Http := TIdHTTP.Create; Strm := TFileStream.Create(Dest, fmCreate); With Http, Strm Do Try Try Get(FUrl, Strm); Result := (Size > 0); Except end; Finally Strm.Free; Http.Free; end; end; 

What do you experts think about using this or that type (memystream or filestream)? Is there any difference in the structure of an EXE file when using this or that type? Which type is recommended?

Thanks! Good weekend!

+6
source share
2 answers

There is no difference between TMemoryStream or TFileStream in terms of stream.

They are both streams and contain a stream of bytes and both are obtained from TStream .

You can implement your generalized function as follows

 function DownloadToStream( const AUrl : String; ADest : TStream ): Boolean; var LHttp: TIdHTTP; begin LHttp := TIdHTTP.Create; try LHttp.Get( AUrl, ADest ); Result := ADest.Size > 0; finally LHttp.Free; end; end; 

and name him

 var LStream : TStream; begin LStream := TFileStream.Create( 'MyFile.exe', fmCreate ); if DownloadToStream( '', LStream ) then ... end; 

or TMemoryStream or any other stream instance that you like

+5
source

In many cases, it makes no sense to put an intermediate memory stream between the download and the file. All that will be done is memory, because you have to put the whole file in memory before you can put it on disk. Using a file stream avoids this problem.

The main situation when the problem with the file stream has problems is that you want to be sure that you have successfully downloaded the entire file before saving to disk. For example, if you overwrite a previous version of a file, you can download it, verify the hash signature, and only then overwrite the original file. In this case, you need to put the file in some temporary place before overwriting. You can use a memory stream or use a file stream using a temporary file name.

+1
source

Source: https://habr.com/ru/post/944279/


All Articles