Click here to Skip to main content
15,881,424 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)
1 Nov 2013CPOL 167K   80   37
This post shows how to create a zip package using System.IO.Compressio.

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)
      {
        // fix for white spaces in file names (by ErrCode)
        Uri fileUri = PackUriHelper.CreatePartUri(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())
      {
        // fix for white spaces in file names (by ErrCode)
        string path = Path.Combine(baseFolder, 
             Uri.UnescapeDataString(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)


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

 
SuggestionRe: Sorry. I got it working. This is due to the white space in S... Pin
ErrCode31-Oct-13 19:31
professionalErrCode31-Oct-13 19:31 
GeneralRe: Sorry. I got it working. This is due to the white space in S... Pin
Tecfield1-Nov-13 1:34
Tecfield1-Nov-13 1:34 
GeneralThere is no license mentioned here. Can one use this code in... Pin
Ivan Ičin23-Jan-12 13:37
Ivan Ičin23-Jan-12 13:37 
GeneralRe: Its license is "The Code Project Open License (CPOL)". Pin
Tecfield23-Jan-12 16:55
Tecfield23-Jan-12 16:55 
GeneralRe: it's a general library tip, you can anywy always use that in... Pin
ThatsAlok24-Jan-12 1:53
ThatsAlok24-Jan-12 1:53 
GeneralThanks for the code, it works great and saves me from having... Pin
bunny ear tv19-Jan-12 3:35
bunny ear tv19-Jan-12 3:35 
GeneralOK, I stand Corrected! I do apologize to the author. Just ... Pin
rcooley16-Jan-12 5:48
rcooley16-Jan-12 5:48 
GeneralReason for my vote of 5 OK, I was wrong. I apologize to the ... Pin
rcooley16-Jan-12 5:46
rcooley16-Jan-12 5:46 
Reason for my vote of 5
OK, I was wrong. I apologize to the Author! I forgot to add the WIndowsBase.dll reference
GeneralIt is generally not a good practice to reference items off o... Pin
Andrew Rissing16-Jan-12 4:25
Andrew Rissing16-Jan-12 4:25 
GeneralRe: yes that's very true and been fixed :) thanks Pin
Tecfield16-Jan-12 5:24
Tecfield16-Jan-12 5:24 
GeneralReason for my vote of 1 Dosnt Work! Pin
rcooley16-Jan-12 3:32
rcooley16-Jan-12 3:32 
GeneralRe: if you get it to work as I replied to your first post, pleas... Pin
Tecfield16-Jan-12 5:23
Tecfield16-Jan-12 5:23 
GeneralIt Dosnt work! It can't Identify the "using System.IO.Pack... Pin
rcooley16-Jan-12 3:31
rcooley16-Jan-12 3:31 
GeneralRe: the very first line says: To use System.IO.Compression, you ... Pin
Tecfield16-Jan-12 5:22
Tecfield16-Jan-12 5: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.