Click here to Skip to main content
13,549,148 members
Click here to Skip to main content
Add your own
alternative version


69 bookmarked
Posted 20 Feb 2007
Licenced CPOL

Zip/Unzip using the .NET namespace and more

, 12 Feb 2013
Rate this:
Please Sign up or sign in to vote.
Zip/Unzip using from managed code.

Screenshot - zipstrip2.png

Table of Contents

  • Introduction
  • Background
  • Listing the content of a Zip file
  • Zipping files from a folder
  • Unzipping files from a Zip file
  • Changing the Zip file
  • Improvements over version 1.0
  • Using the wild chars for the filter
  • Explorer folder context menu
  • History


    When dealing with Zip files, you have a few choices: use native APIs from third party DLLs, Java APIs, or .NET APIs. If you rush to use APIs from the System.IO.Compress .NET namespace, you will be very disappointed. For reasons only Microsoft knows, the support is limited to streams only, and lacks completely for multi-file archives. This was probably a reason why third party .NET libraries like SharpZipLib cropped up. If you don't trust the free software, you might be surprised to find out that you can find .NET support for multi-file archives in .NET buried in J# assemblies that offer parity with Java APIs. To make a useful application that uses it, I started with an existing CodeProject application that is very handy when backing up source code. I replaced the SharpZipLib references and used the Microsoft J# APIs instead. When porting the application, I noticed that the SharpZipLib APIs were looking very similar with the J# APIs, and that made my work so much easier. To make this utility more enticing to use, I've added quite a few features that I will detail below.


    In order to use Microsoft's API for multi-file zips and Java streams, you have to add the vjslib.dll and vjslibcw.dll .NET assemblies as project references. They are part of the J# distribution pack. The Java like types will show up in the namespace. Since Microsoft's documentation on this topic is quite sparse, I often had to rely on intellisense to figure it out. For simplicity's sake, some nonessential UI code is omitted below, and can be found only in the source code provided.

    Listing the content of a Zip file

    Below, you could see a snippet of code edited for simplicity that enumerates the files in the archive:

    public static List<string > GetZipFileNames(string zipFile)
        ZipFile zf = null;
        List<string > list = new List<string >();
            zf = new ZipFile(zipFile);
            java.util.Enumeration enu = zf.entries();
            while (enu.hasMoreElements())
                ZipEntry zen = enu.nextElement() as ZipEntry;
                if (zen.isDirectory())
                    continue;//ignore directories
        catch(Exception ex) 
            throw new ApplicationException("Please drag/drop only valid " 
                      "zip files\nthat are not password protected.",ex);
            if (zf != null)
        return list;

    As you probably noticed, ZipEntry and ZipFile are easy to use for this goal.

    Zipping files from a folder

    Below, you could see a helper method used to Zip files from a folder:

    private static void _CreateZipFromFolder(string Folder, IsFileStrippableDelegate IsStrip)
        System.IO.DirectoryInfo dirInfo =
            new System.IO.DirectoryInfo(Folder);
        System.IO.FileInfo[] files = dirInfo.GetFiles("*");//all files
        foreach (FileInfo file in files)
            if (IsStrip != null && IsStrip(file.FullName))
                continue;//skip, don't zip it
   instream = new;
            int bytes = 0;
            string strEntry = file.FullName.Substring(m_trimIndex);
            _zos.putNextEntry(new ZipEntry(strEntry));
            while ((bytes =, 0, _buffer.Length)) > 0)
                _zos.write(_buffer, 0, bytes);
        System.IO.DirectoryInfo[] folders = null;
        folders = dirInfo.GetDirectories("*");
        if (folders != null)
            foreach (System.IO.DirectoryInfo folder in folders)
                _CreateZipFromFolder(folder.FullName, IsStrip);

    The IsStrip delegate acts as a filter that trashes the unwanted files.

    Unzipping files from a Zip file

    Below, you could see an edited for brevity piece of code used to unzip the files from a Zip:

    ZipInputStream zis = null;
    zis = new ZipInputStream(new;
    ZipEntry ze = null;
    while ((ze = zis.getNextEntry()) != null)
        if (ze.isDirectory())
            continue;//ignore directories
        string fname = ze.getName();
        bool bstrip = IsStrip != null && IsStrip(fname);
        if (!bstrip)
            //unzip entry
            int bytes = 0;
            FileStream filestream = null;
            BinaryWriter w = null;
            string filePath = Folder + @"\" + fname;
            filestream = new FileStream(filePath, FileMode.Create);
            w = new BinaryWriter(filestream);
            while ((bytes =, 0, _buffer.Length)) > 0)
                for (int i = 0; i < bytes; i++)
        if (zis != null)

    Again, the IsStrip delegate acts as a filter that trashes the unwanted files. Also, I had to mix with the System.IO namespace because of the sbyte[] array.

    Changing the Zip file

    You can not directly modify a Zip file. However, you can create another Zip and copy only select files in it. When the transfer is complete, we can rename the new file as the original and it would look like we changed the Zip. The edited for brevity method below receives a list of strings with the unwanted files:

    public static void StripZip(string zipFile, List<string > trashFiles)
        ZipOutputStream zos = null;
        ZipInputStream zis = null;
        //remove 'zip' extension
        bool bsuccess = true;
        string strNewFile = zipFile.Remove(zipFile.Length - 3, 3) + "tmp";
        zos = new ZipOutputStream(new;
        zis = new ZipInputStream(new;
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null)
            if (ze.isDirectory())
                continue;//ignore directories
            string fname = ze.getName();
            bool bstrip = trashFiles.Contains(fname);
            if (!bstrip)
                //copy the entry from zis to zos
                int bytes = 0;
                //deal with password protected files
                zos.putNextEntry(new ZipEntry(fname));
                while ((bytes =, 0, _buffer.Length)) > 0)
                    zos.write(_buffer, 0, bytes);
        if (zis != null)
        if (zos != null)
        if (bsuccess)
            System.IO.File.Delete(zipFile + ".old");
            System.IO.File.Move(zipFile, zipFile + ".old");
            System.IO.File.Move(strNewFile, zipFile);

    Improvements over version 1.0

    To make this tool more attractive, I've added some improvements of my own: The first one to notice is the usage of a checked list box that allows doing manual changes on the fly. My favorite is the ability to edit the list of filter extensions that are bound to the CPZipStripper.exe.xml file through a DataTable. Here is an edited snapshot of this file:

      <maskRow maskField="*.plg" / >
      <maskRow maskField=".opt" / >
      <maskRow maskField=".ncb" / >
      <maskRow maskField=".suo" / >
      <maskRow maskField="*.pdb" / >

    Reading data from the config file

    Notice that in the application configuration file, we keep not only the appSetttings node, but also the files, paths, and most importantly, the DataTable content. Loading the data from this XML file in the respective lists and the DataSet is easy:

    XmlDocument xd = new XmlDocument();
    //use plain xml xpath for the rest
    XmlNode xnpath = xd["configuration"]["paths"];
        foreach(XmlNode xn in xnpath.ChildNodes)
    XmlNode xnfile = xd["configuration"]["files"];
        foreach(XmlNode xn in xnfile.ChildNodes)
    //use the data set
    _dataSet = new DataSet("configuration");
    DataTable mytable = new DataTable("maskRow");
    DataColumn exColumn = new DataColumn("maskField", 
        Type.GetType("System.String"), null, MappingType.Attribute);
    for (int i = 0; i < _dataSet.Tables[0].Rows.Count; i++)
        DataRow row = _dataSet.Tables[0].Rows[i];
        string val = row[0].ToString().ToLower();
        if (val.Length > 0)//no empty mask
        //.....code eliminated for brevity
        {   //don't show empty rows

    Writing data into the config file

    Using WriteXml from the DataSet will eliminate the data that does not belong to the table. For this reason, we have to save it before calling WriteXml, and restore it afterwards:

    XmlDocument xd = new XmlDocument();
    //get the original
    //save nodes not part of the dataset
    XmlNode xnpath = xd["configuration"]["paths"];
    XmlNode xnfile = xd["configuration"]["files"];
    XmlNode lastFolderpath = xd["configuration"]["LastUsedFolder"];
    //write the masks
    //restore the old saved nodes
    if(xnpath != null)
    if (xnfile != null)
    if (lastFolderpath != null)

    Using the wild chars for the filter

    I'm not going to get into the details on this one, but as you've already noticed in the XML snippet, you can use the * and ? chars. It's a good idea that the first thing you do when you open this application is setting the configuration.

    Screenshot - config.png

    Explorer folder context menu

    I've added some new functionality in regards to using the context menu from Explorer. You should start the exe only once before you can right click on the folder and zip it.

    Screenshot - Menu.png


    As a utility, I consider version 2.x to be an improvement over the old one. You can use it to some extent as a WinZip replacement, but it lacks features like encryption. .NET 2.0 and the J# package have to be installed on your machine to run it. If you have problems running the exe alone, it might be because you are missing the J# distribution package or the .NET 2.0 runtime. If that's the case, I recommend you try to install this MSI install file I've created or download and install it locally.

    Version 2.3

    I've added email capability to the application using the Outlook wrapper and made a few small enhancements. I have also included the deployment project that creates the MSI file.

    Version 2.4

    I've forced the assembly to run in 32 bit mode to avoid some 64 bit issues and added some custom actions for the installer.


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


About the Author

Software Developer (Senior)
United States United States
Decebal Mihailescu is a software engineer with interest in .Net, C# and C++.

You may also be interested in...


Comments and Discussions

QuestionHow about DotNetZip? Pin
wmjordan12-Feb-13 15:09
memberwmjordan12-Feb-13 15:09 
AnswerRe: How about DotNetZip? Pin
dmihailescu13-Feb-13 4:27
memberdmihailescu13-Feb-13 4:27 
GeneralRe: How about DotNetZip? Pin
wmjordan13-Feb-13 16:37
memberwmjordan13-Feb-13 16:37 
GeneralRe: How about DotNetZip? Pin
dmihailescu14-Feb-13 2:44
memberdmihailescu14-Feb-13 2:44 
QuestionSystem.IO.Packaging Pin
xoox11-Feb-13 15:33
memberxoox11-Feb-13 15:33 
AnswerRe: System.IO.Packaging Pin
dmihailescu12-Feb-13 5:43
memberdmihailescu12-Feb-13 5:43 
yes, but io.packaging was not available in .net 2.0 days. Frown | :(
It would make sense to use it if I would start from scratch today.
GeneralRe: System.IO.Packaging Pin
Cindy Meister13-Feb-13 6:43
memberCindy Meister13-Feb-13 6:43 
GeneralError while deleting archived files manually Pin
GISDevil21-Apr-08 12:11
memberGISDevil21-Apr-08 12:11 
GeneralRe: Error while deleting archived files manually Pin
dmihailescu24-Apr-08 13:02
memberdmihailescu24-Apr-08 13:02 
GeneralRe: Error while deleting archived files manually Pin
GISDevil28-Apr-08 5:27
memberGISDevil28-Apr-08 5:27 
GeneralRe: Error while deleting archived files manually Pin
dmihailescu28-Apr-08 12:59
memberdmihailescu28-Apr-08 12:59 
GeneralRe: Error while deleting archived files manually Pin
GISDevil29-Apr-08 8:17
memberGISDevil29-Apr-08 8:17 
GeneralRe: Error while deleting archived files manually Pin
dmihailescu29-Apr-08 15:05
memberdmihailescu29-Apr-08 15:05 
QuestionException in ZipFile Pin
HASEENAA14-Feb-08 0:51
memberHASEENAA14-Feb-08 0:51 
GeneralRe: Exception in ZipFile Pin
dmihailescu15-Feb-08 10:36
memberdmihailescu15-Feb-08 10:36 
Questionget folder Pin
manhnhien20911-May-07 16:16
membermanhnhien20911-May-07 16:16 
GeneralGetfolder Pin
manhnhien20911-May-07 16:09
membermanhnhien20911-May-07 16:09 
GeneralMicrosoft.VisualStudio.Zip Pin
David Hay7-Mar-07 15:59
memberDavid Hay7-Mar-07 15:59 
GeneralRe: Microsoft.VisualStudio.Zip Pin
dmihailescu28-Mar-07 11:02
memberdmihailescu28-Mar-07 11:02 
GeneralRe: Microsoft.VisualStudio.Zip Pin
Adam Tibi17-Apr-07 2:54
memberAdam Tibi17-Apr-07 2:54 
GeneralAbout Documentation Pin
Hawk77727-Feb-07 17:00
memberHawk77727-Feb-07 17:00 
GeneralArchive Size Pin
Jamsey1200127-Feb-07 3:07
memberJamsey1200127-Feb-07 3:07 
GeneralRe: Archive Size Pin
dmihailescu28-Feb-07 4:00
memberdmihailescu28-Feb-07 4:00 
GeneralRe: Archive Size Pin
Jamsey1200128-Feb-07 4:04
memberJamsey1200128-Feb-07 4:04 
GeneralRe: Archive Size Pin
Aleksei Krassovskikh17-May-08 9:25
memberAleksei Krassovskikh17-May-08 9:25 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03-2016 | 2.8.180515.1 | Last Updated 12 Feb 2013
Article Copyright 2007 by dmihailescu
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid