Click here to Skip to main content
15,887,027 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 167.5K   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

 
PraiseAwesome and thank you Pin
Avi Farah22-Nov-19 14:00
Avi Farah22-Nov-19 14:00 
QuestionSystem.IO.FileNotFoundException: Could not find file 'C:\Windows\system32\[file to zip] Pin
mtoha15-Feb-16 19:43
professionalmtoha15-Feb-16 19:43 
QuestionHow about folders Pin
pishkari24-Sep-14 0:35
pishkari24-Sep-14 0:35 
GeneralArticle with demo of compression. Pin
DaveAuld1-Nov-13 6:56
professionalDaveAuld1-Nov-13 6:56 
GeneralRe: Article with demo of compression. Pin
Tecfield1-Nov-13 7:59
Tecfield1-Nov-13 7:59 
GeneralMy vote of 3 Pin
BillWoodruff15-Jul-13 18:25
professionalBillWoodruff15-Jul-13 18:25 
... edit: suggestion: clarify for the reader that the purpose of this example is to create a zipped folder (package) from a set of files, or to unzip a set of zipped files in a zipped folder (package) ...

0. In spite of the fact that WindowsBase.dll is notoriously hard to find [^], the author doesn't bother to mention that, or help the reader find it.

1. the author of this article states, in a response, to a message: "There is an alternate version for .NET 3.5 in this thread. Please check it out." There is no alternate version link in this article, or the comments.

2. there are alternate methods, clearly documented by MSDN, that do not require a reference to WindowsBase.dll.

Note that in .NET 4.5 "WindowsBase.dll" is considered an "obsolete" Type: [^], which does not mean this cannot work in 4.5.

fyi: on my current system (Win 8/64), Visual Studio 2012. There are 37 instances of WindowsBase.dll ! Some are specific to WPF.

Have a few:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client\WindowsBase.dll

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\WindowsBase.dll

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\WindowsBase.dll

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll

C:\Windows\assembly\GAC_MSIL\WindowsBase\3.0.0.0__31bf3856ad364e35\WindowsBase.dll

C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\WindowsBase.dll

C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF\WindowsBase.dll

modified 16-Jul-13 1:16am.

GeneralRe: My vote of 3 Pin
Tecfield16-Jul-13 3:09
Tecfield16-Jul-13 3:09 
GeneralRe: My vote of 3 Pin
BillWoodruff24-Jul-13 23:34
professionalBillWoodruff24-Jul-13 23:34 
GeneralRe: My vote of 3 Pin
Tecfield25-Jul-13 3:03
Tecfield25-Jul-13 3:03 
GeneralMy vote of 5 Pin
Abey Thomas2-Nov-12 20:44
Abey Thomas2-Nov-12 20:44 
QuestionCopy Stream Pin
Paul_Williams31-Oct-12 12:39
Paul_Williams31-Oct-12 12:39 
AnswerRe: Copy Stream Pin
Tecfield1-Nov-12 3:13
Tecfield1-Nov-12 3:13 
Questionpackage.GetParts() issue in UnzipFilesFromStream Pin
Ayusman110-Aug-12 2:39
Ayusman110-Aug-12 2:39 
AnswerRe: package.GetParts() issue in UnzipFilesFromStream Pin
Tecfield10-Aug-12 3:08
Tecfield10-Aug-12 3:08 
GeneralRe: Sorry, no malice intended here, but this is a general commen... Pin
Darren Doody26-Jan-12 15:14
professionalDarren Doody26-Jan-12 15:14 
GeneralReason for my vote of 5 this is better than j . Pin
javaevangelist7-Feb-12 8:39
javaevangelist7-Feb-12 8:39 
GeneralNice, but please specify .NET version required. In the titl... Pin
Darren Doody26-Jan-12 13:00
professionalDarren Doody26-Jan-12 13:00 
GeneralRe: As long as you can make a reference to <code>WindowsBase.dll... Pin
Tecfield26-Jan-12 15:05
Tecfield26-Jan-12 15:05 
GeneralReason for my vote of 5 Nice example Pin
loctrice24-Jan-12 9:09
professionalloctrice24-Jan-12 9:09 
GeneralVery nice. It does not handle subdirectories (at least not i... Pin
loctrice24-Jan-12 9:08
professionalloctrice24-Jan-12 9:08 
GeneralReason for my vote of 5 it is nice one. works with out any t... Pin
venkata124-Jan-12 5:16
venkata124-Jan-12 5:16 
GeneralThank you very much for the good article. But I tried to zip... Pin
venkata124-Jan-12 5:10
venkata124-Jan-12 5:10 
GeneralRe: Sorry. I got it working. This is due to the white space in S... Pin
venkata124-Jan-12 5:14
venkata124-Jan-12 5:14 
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 

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.