Click here to Skip to main content
12,078,489 members (46,496 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

85.2K views
77 bookmarked
Posted

Zipping using System.IO.Compression

, 26 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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...

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! Smile | :)

License

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

Share

About the Author

Tecfield
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.

You may also be interested in...

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionHow about folders Pin
pishkari24-Sep-14 1:35
memberpishkari24-Sep-14 1:35 
GeneralArticle with demo of compression. Pin
DaveAuld1-Nov-13 7:56
protectorDaveAuld1-Nov-13 7:56 
GeneralRe: Article with demo of compression. Pin
Tecfield1-Nov-13 8:59
memberTecfield1-Nov-13 8:59 
GeneralMy vote of 3 Pin
BillWoodruff15-Jul-13 19:25
memberBillWoodruff15-Jul-13 19:25 
GeneralRe: My vote of 3 Pin
Tecfield16-Jul-13 4:09
memberTecfield16-Jul-13 4:09 
GeneralRe: My vote of 3 Pin
BillWoodruff25-Jul-13 0:34
memberBillWoodruff25-Jul-13 0:34 
GeneralRe: My vote of 3 Pin
Tecfield25-Jul-13 4:03
memberTecfield25-Jul-13 4:03 
GeneralMy vote of 5 Pin
Abey Thomas2-Nov-12 21:44
memberAbey Thomas2-Nov-12 21:44 
QuestionCopy Stream Pin
Paul @ The Computer Station31-Oct-12 13:39
groupPaul @ The Computer Station31-Oct-12 13:39 
AnswerRe: Copy Stream Pin
Tecfield1-Nov-12 4:13
memberTecfield1-Nov-12 4:13 
Questionpackage.GetParts() issue in UnzipFilesFromStream Pin
Ayusman110-Aug-12 3:39
memberAyusman110-Aug-12 3:39 
AnswerRe: package.GetParts() issue in UnzipFilesFromStream Pin
Tecfield10-Aug-12 4:08
memberTecfield10-Aug-12 4:08 
GeneralRe: Sorry, no malice intended here, but this is a general commen... Pin
Darren Doody26-Jan-12 16:14
memberDarren Doody26-Jan-12 16:14 
GeneralReason for my vote of 5 this is better than j . Pin
javaevangelist7-Feb-12 9:39
memberjavaevangelist7-Feb-12 9:39 
GeneralNice, but please specify .NET version required. In the titl... Pin
Darren Doody26-Jan-12 14:00
memberDarren Doody26-Jan-12 14:00 
GeneralRe: As long as you can make a reference to <code>WindowsBase.dll... Pin
Tecfield26-Jan-12 16:05
memberTecfield26-Jan-12 16:05 
GeneralReason for my vote of 5 Nice example Pin
loctrice24-Jan-12 10:09
memberloctrice24-Jan-12 10:09 
GeneralVery nice. It does not handle subdirectories (at least not i... Pin
loctrice24-Jan-12 10:08
memberloctrice24-Jan-12 10:08 
GeneralReason for my vote of 5 it is nice one. works with out any t... Pin
venkata124-Jan-12 6:16
membervenkata124-Jan-12 6:16 
GeneralThank you very much for the good article. But I tried to zip... Pin
venkata124-Jan-12 6:10
membervenkata124-Jan-12 6:10 
GeneralRe: Sorry. I got it working. This is due to the white space in S... Pin
venkata124-Jan-12 6:14
membervenkata124-Jan-12 6:14 
SuggestionRe: Sorry. I got it working. This is due to the white space in S... Pin
ErrCode31-Oct-13 20:31
memberErrCode31-Oct-13 20:31 
GeneralRe: Sorry. I got it working. This is due to the white space in S... Pin
Tecfield1-Nov-13 2:34
memberTecfield1-Nov-13 2:34 
GeneralThere is no license mentioned here. Can one use this code in... Pin
ivanicin23-Jan-12 14:37
memberivanicin23-Jan-12 14:37 
GeneralRe: Its license is "The Code Project Open License (CPOL)". Pin
Tecfield23-Jan-12 17:55
memberTecfield23-Jan-12 17:55 
GeneralRe: it's a general library tip, you can anywy always use that in... Pin
ThatsAlok24-Jan-12 2:53
memberThatsAlok24-Jan-12 2:53 
GeneralThanks for the code, it works great and saves me from having... Pin
bunny ear tv19-Jan-12 4:35
memberbunny ear tv19-Jan-12 4:35 
GeneralOK, I stand Corrected! I do apologize to the author. Just ... Pin
rcooley16-Jan-12 6:48
memberrcooley16-Jan-12 6:48 
GeneralReason for my vote of 5 OK, I was wrong. I apologize to the ... Pin
rcooley16-Jan-12 6:46
memberrcooley16-Jan-12 6:46 
GeneralIt is generally not a good practice to reference items off o... Pin
Andrew Rissing16-Jan-12 5:25
memberAndrew Rissing16-Jan-12 5:25 
GeneralRe: yes that's very true and been fixed :) thanks Pin
Tecfield16-Jan-12 6:24
memberTecfield16-Jan-12 6:24 
GeneralReason for my vote of 1 Dosnt Work! Pin
rcooley16-Jan-12 4:32
memberrcooley16-Jan-12 4:32 
GeneralRe: if you get it to work as I replied to your first post, pleas... Pin
Tecfield16-Jan-12 6:23
memberTecfield16-Jan-12 6:23 
GeneralIt Dosnt work! It can't Identify the "using System.IO.Pack... Pin
rcooley16-Jan-12 4:31
memberrcooley16-Jan-12 4:31 
GeneralRe: the very first line says: To use System.IO.Compression, you ... Pin
Tecfield16-Jan-12 6:22
memberTecfield16-Jan-12 6:22 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160212.1 | Last Updated 26 Jan 2012
Article Copyright 2012 by Tecfield
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid