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.
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";
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.
- Original post: 29 August, 2013