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 5memberAbey Thomas2 Nov '12 - 20:44 
Nice tip. I will be using this someday Smile | :)
QuestionCopy StreamgroupPaul @ The Computer Station31 Oct '12 - 12:39 
Hi,
 
Just reading though your code. I am a VB programmer, so may have missed something trying to understand C#.
 
Can your method CopyStream not be simplified to source.CopyTo(destination) or source.CopyTo(destination, bufferSize)?
 
Cheers,
 
Paul
AnswerRe: Copy StreammemberTecfield1 Nov '12 - 3:13 
You are absolutely right. Totally missed that method. I'll fix it. Thanks Smile | :)
Maybe I, Maybe U, can make a change to the world!

Questionpackage.GetParts() issue in UnzipFilesFromStreammemberAyusman110 Aug '12 - 2:39 
Hi,
I gone through your code and try to implement the same. But it's not working for me to unzip a zipfile.
 
I am pasing parameters zipPath and baseFolder to Unzip() method.
When controls pass to "UnzipFilesFromStream(Stream source, string baseFolder)" method, in "foreach (PackagePart zipPart in package.GetParts())" section, i didn't get anything and control comes out from foreach loop.
I think either "using (Package package = Package.Open(source, FileMode.Open))" or package.GetParts() is not working properly.
 
Please guide me.
 
Thanks in advance.
AnswerRe: package.GetParts() issue in UnzipFilesFromStreammemberTecfield10 Aug '12 - 3:08 
Hi,
 
Make sure you set the file position to the beginning of the file before you call UnzipFilesFromStream(Stream source, string baseFolder). If that doesn't fix it and you have altered the code presented in the tip, copy and paste your code in the message so I can take a look and figure out what might be wrong.
 

Cheers
Maybe I, Maybe U, can make a change to the world!

GeneralRe: Sorry, no malice intended here, but this is a general commen...memberDarren Doody26 Jan '12 - 15:14 
Sorry, no malice intended here, but this is a general comment for yourself and all posters. The application I develop is targeted at .Net 2.0. As such, no version of WindowsBase.dll is available to me, so your article really needs to EXCLUDE versions pre-3.0. It is an interesting article, and may come in useful to me - someday - but when looking for a solution to a problem, I don't want to read a whole article, then try and implement it only to find I can't because it's targeted at a later framework. We don't all have the luxury of choosing the version of the framework we are working with.
GeneralReason for my vote of 5 this is better than j .memberjavaevangelist7 Feb '12 - 8:39 
Reason for my vote of 5
this is better than j .
GeneralNice, but please specify .NET version required. In the titl...memberDarren Doody26 Jan '12 - 13:00 
Nice, but please specify .NET version required. In the title, or with Code Project flags or, at a minimum, early in the text. Those of us stuck with using early versions of .NET then need not waste our time. Thanks.
GeneralRe: As long as you can make a reference to <code>WindowsBase.dll...memberTecfield26 Jan '12 - 15:05 
As long as you can make a reference to WindowsBase.dll you should be able to use this code. You may need to change method signatures a little bit though. There is an alternate version for .NET 3.5 in this thread. Please check it out Smile | :)
GeneralReason for my vote of 5 Nice examplememberloctrice24 Jan '12 - 9:09 
Reason for my vote of 5
Nice example

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

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