Thursday, 12 November 2009

Zip up a directory and download to client

I googled about this and found some pretty contrived ways of doing it, especially when it came to honouring subdirectories and their structure. Eventually I discovered the FastZip class of the ICSharpCode.SharpZipLib.Zip library that makes it very easy.

And here's my code. Send it the path of the dir to be zipped and the desired name of the resulting zip file:

Public Sub ZipAndDownload(ByVal strPath As String, ByVal strFileName As String)

HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName & ".zip")

'FastZip - zip all the file and folders
'and stream it through the Response OutputStream
Dim fz As New ICSharpCode.SharpZipLib.Zip.FastZip()
fz.CreateZip(HttpContext.Current.Response.OutputStream, strPath, True, Nothing, Nothing)

End Sub

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!