Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Compress/Decompress Zip Files without Third-party Libraries in C#

0.00/5 (No votes)
29 Aug 2013 1  
This is an alternative for Compress Zip files with Windows Shell API and C#

Introduction

This is a follow-up to the article "Compress Zip files with Windows Shell API and C#" by "Gerald Gibson Jr".

I needed a similar functionality for a very basic compression/decompression and didn't want to use any third party libraries. Out of the many options that I came up with, I thought the Windows Shell API served best for my purpose.

Granted, that this is not the best way to archive/un-archive files, but I found this to be one of the simplest ways to achieve what I needed.

Background

What I'm presenting here is a simple wrapper class for archiving/un-archiving using the Windows Shell API with (very) minimal error handling. Additionally, I've also included a function to copy the file permissions from one file to another. This might be useful in some cases.

Using the Code

As the class uses the Shell32 namespace, a reference to Microsoft Shell Controls and Automation should be added to the project. This would come under the COM references section. The wrapper class is named ArchiveManager and has a few public static methods that expose the functionalities.

public static bool Archive(string archiveFile, string unArchiveFolder);
public static bool UnArchive(string archiveFile);
public static bool UnArchive(string archiveFile, string unArchiveFolder);
public static bool CopyPermissions(string sourceFile, string destFile) ;

The method names are pretty self explanatory, however a sample console application has been included in the accompanying code which shows sample usage of the wrapper class.

string _sourceFile = "Template.zip";
if (!ArchiveManager.UnArchive(_sourceFile))
{  
   Console.WriteLine("ERROR: " + ArchiveManager.LastError);
}

Other methods can be used in a similar way.

Points of Interest

One of the issues with this approach is that the Shell32 APIs used to create/extract an archive are asynchronous. Meaning, our main thread cannot determine when the archiving/extracting methods are complete.

A rather crude approach has been used to get around this problem. I've used a wait loop that keeps sleeping till the number of items in the source folder (or zip file) and destination folder (or zip file) are equal, or, a timeout (configurable) occurs.

History

  • Original post: 29 August, 2013

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here