Using an instance of
TMemoryStream as an intermediate storage is a common approach. But it is not safe to use a memory stream when the content is too large, otherwise the application may run out of memory and crash.
The only safe approach for handling an intermediate storage, is to use a temporary file. Of course, using a temporary file is not as easy as using a memory stream. Because, we need to write code to get a unique file name, create the file and finally delete it when it is no more needed.
Here, I am going to introduce you a stream class named
TTemporaryFileStream. This class takes care of creating and deleting the temporary file and we can use it as easy as a memory stream.
type TTemporaryFileStream = class(THandleStream) public constructor Create; end; constructor TTemporaryFileStream.Create; var TempPath: array[0..MAX_PATH] of AnsiChar; TempFile: array[0..MAX_PATH] of AnsiChar; TempHandle: THandle; begin GetTempPathA(High(TempPath), TempPath); GetTempFileNameA(TempPath, 'DA', 0, TempFile); TempHandle := CreateFileA(TempFile, GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_RANDOM_ACCESS or FILE_FLAG_DELETE_ON_CLOSE, 0); Assert(TempHandle <> INVALID_HANDLE_VALUE, 'Unable to create temporary file'); inherited Create(TempHandle); end;