Click here to Skip to main content
Click here to Skip to main content

Zipping using System.IO.Compression

By , 1 Nov 2012
 
To use System.IO.Compression, you need to add a reference to WindowsBase.dll.
 
The following code snippet shows how to use some of the provided functionalities: 
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
 
public static class ZipHelper
{
    public static void ZipFiles(string path, IEnumerable<string> files, CompressionOption compressionLevel = CompressionOption.Normal)
    {
        using (FileStream fileStream = new FileStream(path, FileMode.Create))
        {
            ZipHelper.ZipFilesToStream(fileStream, files, compressionLevel);
        }
    }
 
    public static byte[] ZipFilesToByteArray(IEnumerable<string> files, CompressionOption compressionLevel = CompressionOption.Normal)
    {
        byte[] zipBytes = default(byte[]);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            ZipHelper.ZipFilesToStream(memoryStream, files, compressionLevel);
            memoryStream.Flush();
            zipBytes = memoryStream.ToArray();
        }
 
        return zipBytes;
    }
 
    public static void Unzip(string zipPath, string baseFolder)
    {
        using (FileStream fileStream = new FileStream(zipPath, FileMode.Open))
        {
            ZipHelper.UnzipFilesFromStream(fileStream, baseFolder);
        }
    }
 
    public static void UnzipFromByteArray(byte[] zipData, string baseFolder)
    {
        using (MemoryStream memoryStream = new MemoryStream(zipData))
        {
            ZipHelper.UnzipFilesFromStream(memoryStream, baseFolder);
        }
    }
 
    private static void ZipFilesToStream(Stream destination, IEnumerable<string> files, CompressionOption compressionLevel)
    {
        using (Package package = Package.Open(destination, FileMode.Create))
        {
            foreach (string path in files)
            {
                Uri fileUri = new Uri(@"/" + Path.GetFileName(path), UriKind.Relative);
                string contentType = @"data/" + ZipHelper.GetFileExtentionName(path);
 
                using (Stream zipStream = package.CreatePart(fileUri, contentType, compressionLevel).GetStream())
                {
                    using (FileStream fileStream = new FileStream(path, FileMode.Open))
                    {
                        fileStream.CopyTo(zipStream);
                    }
                }
            }
        }
    }
 
    private static void UnzipFilesFromStream(Stream source, string baseFolder)
    {
        if (!Directory.Exists(baseFolder))
        {
            Directory.CreateDirectory(baseFolder);
        }
 
        using (Package package = Package.Open(source, FileMode.Open))
        {
            foreach (PackagePart zipPart in package.GetParts())
            {
                string path = Path.Combine(baseFolder, zipPart.Uri.ToString().Substring(1));
 
                using (Stream zipStream = zipPart.GetStream())
                {
                    using (FileStream fileStream = new FileStream(path, FileMode.Create))
                    {
                        zipStream.CopyTo(fileStream);
                    }
                }
            }
        }
    }
 
    private static string GetFileExtentionName(string path)
    {
        string extention = Path.GetExtension(path);
        if (!string.IsNullOrWhiteSpace(extention) && extention.StartsWith("."))
        {
            extention = extention.Substring(1);
        }
 
        return extention;
    }
}
 
Enjoy it!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Tecfield
Software Developer (Senior)
United States United States
Member
I got my BS in Software Engineering from Iran, worked there for 4.5 years mainly in industrial automation field. Then I moved to Australia. In Australia, I had a great chance to work at some big companies. Since 2009 I have been living in the States. I received my MS in Information Systems from Illinois State University. Currently, I am a Senior Software Development Engineer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 PinmemberAbey Thomas2 Nov '12 - 20:44 
QuestionCopy Stream PingroupPaul @ The Computer Station31 Oct '12 - 12:39 
Questionpackage.GetParts() issue in UnzipFilesFromStream PinmemberAyusman110 Aug '12 - 2:39 
GeneralRe: Sorry, no malice intended here, but this is a general commen... PinmemberDarren Doody26 Jan '12 - 15:14 
GeneralReason for my vote of 5 this is better than j . Pinmemberjavaevangelist7 Feb '12 - 8:39 
GeneralNice, but please specify .NET version required. In the titl... PinmemberDarren Doody26 Jan '12 - 13:00 
GeneralReason for my vote of 5 Nice example Pinmemberloctrice24 Jan '12 - 9:09 
GeneralVery nice. It does not handle subdirectories (at least not i... Pinmemberloctrice24 Jan '12 - 9:08 
GeneralReason for my vote of 5 it is nice one. works with out any t... Pinmembervenkata124 Jan '12 - 5:16 
GeneralThank you very much for the good article. But I tried to zip... Pinmembervenkata124 Jan '12 - 5:10 
GeneralThere is no license mentioned here. Can one use this code in... Pinmemberivanicin23 Jan '12 - 13:37 
GeneralThanks for the code, it works great and saves me from having... Pinmemberbunny ear tv19 Jan '12 - 3:35 
GeneralOK, I stand Corrected! I do apologize to the author. Just ... Pinmemberrcooley16 Jan '12 - 5:48 
GeneralReason for my vote of 5 OK, I was wrong. I apologize to the ... Pinmemberrcooley16 Jan '12 - 5:46 
GeneralIt is generally not a good practice to reference items off o... PinmemberAndrew Rissing16 Jan '12 - 4:25 
GeneralReason for my vote of 1 Dosnt Work! Pinmemberrcooley16 Jan '12 - 3:32 
GeneralIt Dosnt work! It can't Identify the "using System.IO.Pack... Pinmemberrcooley16 Jan '12 - 3:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 1 Nov 2012
Article Copyright 2012 by Tecfield
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid