[TUT] Zip and UnZip Files in VB.NET

Hi all.

This is my tutorial to zip and unzip files.

First of all, create a new project and name it wathever you want.

Then the first thing what you have to do is add the reference that is called WindowBase
[Image: 1.png]

Then Customize your form.. I just let it simple
[Image: 2.png]

Now, double click on the Zip button to switch to your code window.
At the top, type in:

Imports System.IO.Packaging

Then in the Button1_Click sub from the Zip Button, add this code:

'The Path of the Zip file you want to create
Dim zippath As String = IO.Path.Combine(Application.StartupPath, "test.zip")

'Create New Zip File
Dim zip As ZipPackage = ZipPackage.Open(zippath, IO.FileMode.Create, IO.FileAccess.ReadWrite)

To add a file or folder, use this:

Dim part As PackagePart = zip.CreatePart(New Uri("/subfolder/calc.exe", UriKind.Relative), _
                                         Net.Mime.MediaTypeNames.Application.Zip, CompressionOption.Normal)

Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("c:windowssystem32calc.exe")
part.GetStream.Write(bytes, 0, bytes.Length)

And finally, when you are done with adding files and/or folders close the zip creation.


Now you have the zip code, test your program and you will see something like this:

[Image: 3.png]


But it’s not finished yet. We have to unzip the file as well.
To do that, double click on the Unzip Button and the Button2_Click Sub will be generated.

Inside that sub, type this:

Dim zippath As String = IO.Path.Combine(Application.StartupPath, "test.zip")
Dim zip As ZipPackage = ZipPackage.Open(zippath, IO.FileMode.Open, IO.FileAccess.ReadWrite)

'Loop through every Packagepart
For Each p As PackagePart In zip.GetParts

    'Get Filename without path
    Dim FileName As String = p.Uri.ToString.Substring(p.Uri.ToString.LastIndexOf("/") + 1)

    'Create a new FileStream
    Dim tempstream As New IO.FileStream(Application.StartupPath & "" & FileName, IO.FileMode.Create)

    'Copy stream to the tempstream


'And at last

Now test your program and if you did all things right, you will get something like this:

[Image: 4.png]

And that’s all you have to do

You can download the project here:


Virustotal scan


We will be happy to hear your thoughts

Leave a reply