Click here to Skip to main content
15,891,033 members
Articles / Programming Languages / C#
Tip/Trick

Zipping using System.IO.Compression

Rate me:
Please Sign up or sign in to vote.
4.96/5 (32 votes)
5 Feb 2012CPOL 167.7K   80  
This post shows how to create a zip package using System.IO.Compression
This is an old version of the currently published tip/trick.
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:

C#
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))
                    {
                        ZipHelper.CopyStream(fileStream, 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))
                    {
                        ZipHelper.CopyStream(zipStream, fileStream);
                    }
                }
            }
        }
    }

    private static void CopyStream(Stream source, Stream destination)
    {
        const int bufferSize = 0x1000;
        byte[] buffer = new byte[bufferSize];
        int count = 0;

        while ((count = source.Read(buffer, 0, bufferSize)) > 0)
        {
            destination.Write(buffer, 0, count);
        }
    }

    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)


Written By
Architect
United States United States
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.

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.