(NOTE: The code has been updated for better compatibility on Windows Vista and 8.)
Introduction
If you want to zip / unzip files and folders without using third-party libraries, and you need a simple way to do it, then the Windows Shell32 is your choice.
The code is written with Visual Basic 2010 using .NET Framework 2.0 (running on Windows 7 x64), but it's simple and can be easily converted to any other language (like C#).
The Code
The first step is to create an empty ZIP file. Then, by using the CopyHere
method, the files can be copied (or compressed) into the ZIP file. Also, using the same method, we can copy (or extract) the compressed files.
Public Class Form1
Dim outputZip As String = "output zip file path"
Dim inputZip As String = "input zip file path"
Dim inputFolder As String = "input folder path"
Dim outputFolder As String = "output folder path"
Dim shObj As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
Sub Zip()
Dim startBytes() As Byte = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, _
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
FileIO.FileSystem.WriteAllBytes(outputZip, startBytes, False)
Dim input As Object = shObj.NameSpace((inputFolder))
Dim output As Object = shObj.NameSpace((outputZip))
output.CopyHere((input.Items), 4)
End Sub
Sub UnZip()
IO.Directory.CreateDirectory(outputFolder)
Dim output As Object = shObj.NameSpace((outputFolder))
Dim input As Object = shObj.NameSpace((inputZip))
output.CopyHere((input.Items), 4)
End Sub
End Class
In the CopyHere
method, option 4 was used, but it seems that it's actually ignored. Please refer to this page for more details: http://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx.
Note that when using the methods NameSpace
and CopyHere
, the parameters were passed through additional parentheses. For some reason, it seems that there's a problem passing the variables themselves, therefore, the parentheses were used to pass "New" parameters which are created from and equivalent to the original ones. Otherwise, you would receive errors.
(Thanks to Thomas Tsigkonis for reporting the issues he faced on Windows 8.)
For those wondering if this method also compresses files (reduces their size): Yes! It does.
Also, you need to know that since the zipping/unzipping operations are carried-out by the Shell32
itself, you do not have a direct control on them. But, there are couple of ways to monitor the process, some of them are mentioned in the comments below.
At the end, this is an easy and fast-to-implement method for adding zipping / unzipping capabilities to your Windows application.
Best regards!