Home > Software engineering >  In-memory compression of a Zip file
In-memory compression of a Zip file

Time:11-19

I want to compress files into Zip in-memory (I will store the result on a database instead of creating files in the file system).

How can I read the raw content for the compressed Zip file ?. I can't see any property to read that content, or any method to save that content into an Stream or any other in-memory structure.

function GetZip(UncompressedFile: TStream): TBytes; 
var AZipFile: TZipFile;
begin
  AZipFile := TZipFile.Create;
  try
    AZipFile.Add(UncompressedFile);
    Result := AZipFile.Data;  // ?? How to get the compressed file without saving it to the file system ??
  finally
    AZipfile.Free;
  end;
end;

Thank you.

CodePudding user response:

Thanks to AmigoJack and Remy Lebeau for letting me know that I can use the Zip input Stream to also get the result.

This works fine :

function Zip_AddFile(FileToAdd: TStream; Title: string): TBytes; overload; 
begin
   Result := Zip_AddFile([], FileToAdd, Title);
end;

function Zip_AddFile(Zip: TBytes; FileToAdd: TStream; Title: string): TBytes; overload;
var AZipFile: TZipFile;
    ZipStream: TBytesStream;
begin
  ZipStream := TBytesStream.Create(Zip);
  AZipFile := TZipFile.Create;
  try
    AZipFile.Open(ZipStream, zmReadWrite);
    AZipFile.Add(FileToAdd, Title);
    AZipFile.Close;
    Result := ZipStream.Bytes;
  finally
    AZipfile.Free;
    ZipStream.Free;
  end;
end;
  • Related