[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:

Code:
Imports System.IO.Packaging


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

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:

Code:
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.

Code:
zip.close()



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


[Image: 3.png]



Congratulations!

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:

Code:
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
    p.GetStream.CopyTo(tempstream)

    tempstream.Close()
Next

'And at last
zip.Close()


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
Thumbsup

You can download the project here:

http://www.mediafire.com/?1hbffjodefwbj8i

Virustotal scan

http://www.virustotal.com/file-scan/repo…1311628040

We will be happy to hear your thoughts

Leave a reply