How to unzip files in .NET using SharpZipLib

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();
}
If you have any questions or comments, please post them below. If you liked this post, you can share it with your followers or follow me on Twitter!