I'm trying to write a method in my C# MVC project that streams a file from S3 (or anywhere) and compresses it into a zip file on-the-fly before sending the compressed stream to the user. So far I've found several ways to create a zip file from a stream by saving it to disk and then returning it normally, but I'd like to skip the saving to disk and use a buffer to stream approach. I'm trying to download a very large file (4gb+) that is easily compressed to a fraction of its original size.
So far I have this which avoids the disk, but seems to load the entire file into memory first:
using( var memoryStream = new MemoryStream() )
{
using( var archive = new ZipArchive( memoryStream, ZipArchiveMode.Create, true ) )
{
var zipEntry = archive.CreateEntry( File );
using( var entryStream = zipEntry.Open() )
{
S3.StreamFile( File, Bucket ).CopyTo( entryStream );
}
}
return base.File( memoryStream.ToArray(), "application/zip", File + ".zip" );
}
A similar question (Creating a ZIP Archive in Memory Using System.IO.Compression) only has answers that involve writing to disk.