How to unzip files in .NET using SharpZipLib

March 12th, 2008

SharpZipLib is a great open source library for handeling all kinds of gzip/zip compression/decompression. More Info - http://www.icsharpcode.net/OpenSource/SharpZipLib/

In the following example I’m passing the HtmlInputFile object directly into the ZipInputStream to decompress the PostedFile and save its contents on the server.

.
.
using System.IO;
using ICSharpCode.SharpZipLib.Zip
.
.
private void UnzipAndSave(HtmlInputFile objFileUpload)
{
    ZipInputStream s = new ZipInputStream(objFileUpload.PostedFile.InputStream);

    ZipEntry theEntry;
    string virtualPath = “~/uploads/”;
    string fileName = string.Empty;
    string fileExtension = string.Empty;
    string fileSize = string.Empty;

    while ((theEntry = s.GetNextEntry()) != null)
    {
        fileName = Path.GetFileName(theEntry.Name);
        fileExtension = Path.GetExtension(fileName);

        if (!string.IsNullOrEmpty(fileName))
        {
            try
            {
                FileStream streamWriter = File.Create(Server.MapPath(virtualPath + fileName));
                int size = 2048;
                byte[] data = new byte[2048];

                do
                {
                    size = s.Read(data, 0, data.Length);
                    streamWriter.Write(data, 0, size);
                } while (size > 0);

                fileSize = Convert.ToDecimal(streamWriter.Length / 1024).ToString() + ” KB”;

                streamWriter.Close();

                //Add custom code here to add each file to the DB, etc.
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
    }

    s.Close();
}

Programming | Comments | Trackback Jump to the top of this page

Leave a Reply

  •  
  •  
  •  

You can keep track of new comments to this post with the comments feed.


Recently on Flickr

  • IMG_0514
  • IMG_0506
  • IMG_0505
  • IMG_0503
  • IMG_0497
  • IMG_0495
  • IMG_0494
  • IMG_0493

Switch Theme

Meta