8/28/2008
LifeCycle Solutions - Home ( the software development blog )
 

<August 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

Subscribe to this feed:

RSS 2.0 | Atom 1.0 |CDF





Add to Technorati Favorites

Wednesday, December 12, 2007

I recently had an ASP.NET project with the following requirements:

- Build 2 CSV files from SQL Server data based on parameters specified by the user
- Build a ZIP archive containing these files and allow the user to download

It's been a while since I'd worked with ZIP archives in ASP.NET, so I thought I'd share the solution.  One of the best libraries I've found for creating a wide range of compressed files is SharpZipLib. There are numerous examples of compressing files located in the file system with SharpZipLib, but this project required me to build the archive in-memory in order to avoid unnecessary disk I/O.  Here's how it's done:

string summaryResult = BuildOrderSummary(); string detailResult = BuildOrderDetail(); string fileName = "Orders.zip"; Encoding ascii = Encoding.ASCII; MemoryStream memOutput = new MemoryStream(); ZipOutputStream zipOutput = new ZipOutputStream(memOutput); zipOutput.SetLevel(5); //convert the strings into byte arrays byte[] headerFile = ascii.GetBytes(summaryResult); byte[] detailFile = ascii.GetBytes(detailResult); ZipEntry summaryEntry = new ZipEntry("OrderSummary.csv"); ZipEntry detailEntry = new ZipEntry("OrderDetail.csv"); //add the summary file to the ZIP archive summaryEntry.Size = headerFile.Length; zipOutput.PutNextEntry(summaryEntry); zipOutput.Write(headerFile, 0, headerFile.Length); //add the detail file to the ZIP archive detailEntry.Size = detailFile.Length; zipOutput.PutNextEntry(detailEntry); zipOutput.Write(detailFile, 0, detailFile.Length); //clean up the ZIP stream zipOutput.Finish(); zipOutput.Close(); //clean up the memory stream memOutput.Close(); //send the ZIP file back to the user Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "attachment; filename=" + fileName); Response.BinaryWrite(memOutput.ToArray()); Response.Flush(); Response.End();
Posted by Brian Parks

© 2006 LifeCycle Solutions, LLC | All Rights Reserved