Generate zip files on the fly and send it directly to the browser (with ICSharpZipLib)

D

David Hauser

Hi all

I have a aspx page that should generate a zip file from a couple of files. I
tried the following code, but something doesn't work correctly, although no
error message appears and the dialog box for downloading the zip file
appears. But when i try to open the zip file the zip application return an
error like "file is corrupted or not a zip file". Has someone a hint for me
what's wrong with my code? Or knows somebody a good tutorial for
ICSharpZipLib? Thanks.

David Hauser


-----------------------------------
GetZipFile.aspx.cs
-----------------------------------

....
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
....

private void BuildZipFile(string[] FilePaths) // FilePaths = relative
Pfadangaben
{
Crc32 crc = new Crc32();
MemoryStream ms = new MemoryStream();
ZipOutputStream z = new ZipOutputStream(ms);

z.SetLevel(9); // 0 - store only to 9 - means best compression

foreach (string file in FilePaths)
{
string FilePath = Server.MapPath(file);
// Trace.Warn(FilePath);
// --> gibt die richtigen Pfade aus
FileStream fs = File.OpenRead(FilePath);

byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(file);

entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
z.PutNextEntry(entry);
z.Write(buffer, 0, buffer.Length);
}
long ZipFileSize = z.Length;
byte[] b = new byte[(int)ZipFileSize];
ms.Read(b, 0, b.Length);
ms.Close();

Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Length", b.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment;
filename=Download.zip");
Response.BinaryWrite(b);
Response.End();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top