Zip.NET
I was enhancing my mp3 aspx search page to include a shopping cart function. I figured it would be nice to grab all of the mp3 files, zip them up into one big zip file and dump it into the HTTPResponse stream. Well two missing things: A zip library and a way to stream in the files so I don't have to create an actual hard disk based zip file. Here's how I did it:
The zip library can be found here -- SharpZipLib It's open source and a byproduct of the very cool open source SharpDevelop IDE.
Here's the code:
MemoryStream ms = new MemoryStream();
ZipOutputStream s = new ZipOutputStream( ms );
s.SetLevel(5); // 0 - store only to 9 - means best compression
foreach ( int id in ids ) // primary key ids
{
string location = new MP3DataAccess().GetLocation( id );
FileInfo fi = new FileInfo( location );
FileStream fs = File.OpenRead( location );
byte[] buffer = new byte[ fs.Length ];
fs.Read( buffer, 0, buffer.Length );
ZipEntry entry = new ZipEntry( fi.Name );
s.PutNextEntry( entry );
s.Write( buffer, 0, buffer.Length );
}
s.Finish();
int streamLength = (int)ms.Length;
ms.Seek( 0, SeekOrigin.Begin );
ms.Position = 0;
byte[] buffinal = new byte[ streamLength ];
ms.Read( buffinal, 0, streamLength );
ms.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/octet-stream";
Response.AppendHeader( "content-length", streamLength.ToString() );
string uniqueFileName = "mp3s-" + DateTime.Now.ToString( "yyyy-MM-ddTHHmmss" ) + ".zip";
Response.AppendHeader( "content-disposition", "inline; filename=" + uniqueFileName );
Response.BinaryWrite( buffinal );