Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / Visual Basic
Article

Zip Files Easy!

Rate me:
Please Sign up or sign in to vote.
4.63/5 (44 votes)
25 Jul 2008CPOL2 min read 201.3K   11.9K   106   25
The purpose of this article is to demonstrating zipping files using the ZipPackage class in this System.IO.Packaging namespace. This demonstration uses: VB.Net 2008 .Net, Framwork 3.0.

Demo Preview

Image 1

Introduction

Zipping multiple files has never been easier for .Net programmers than it is now with the .Net framework 3.0! Using the new ZipPackage class in the namespace System.IO.Packaging and a few lines of code, you can easily create .zip archives with as many files as you like!

Using the Code

At it's easiest:

  • Add a reference to the "WindowsBase.dll" (Project menu | Add Reference...)

    If you can't find the .dll on the .net tab, then click on the Browse tab, and try looking for it in the following directory:

    • C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\

    If you can't find it there, then you may need to search your system.

  • Add an Imports statement at the top of your class:
    VB.NET
    Imports System.IO.Packaging
    
  • Write some code:

    VB.NET
    Dim zipPath As String = "C:\TEMP\Compression\myzip.zip"
    Dim fileToAdd As String = "C:\TEMP\Compression\Compress Me.txt"
    
    'Open the zip file if it exists, else create a new one
    Dim zip As Package = ZipPackage.Open(zipPath, _
              IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)
    
    'Replace spaces with an underscore (_)
    Dim uriFileName As String = fileToAdd.Replace(" ", "_")
    
    'A Uri always starts with a forward slash "/"
    Dim zipUri As String = String.Concat("/", _
              IO.Path.GetFileName(uriFileName))
    
    Dim partUri As New Uri(zipUri, UriKind.Relative)
    Dim contentType As String = _
              Net.Mime.MediaTypeNames.Application.Zip
    
    'The PackagePart contains the information:
    ' Where to extract the file when it's extracted (partUri)
    ' The type of content stream (MIME type) - (contentType)
    ' The type of compression to use (CompressionOption.Normal)
    Dim pkgPart As PackagePart = _
              zip.CreatePart(partUri, contentType, _
              CompressionOption.Normal)
    
    'Read all of the bytes from the file to add to the zip file
    Dim bites As Byte() = File.ReadAllBytes(fileToAdd)
    
    'Compress and write the bytes to the zip file
    pkgPart.GetStream().Write(bites, 0, bites.Length)
    
    zip.Close() 'Close the zip file
    
  • Refactored code for increased efficiency:

    VB.NET
    Private Sub ZipFiles()
    
        Dim zipPath As String = "C:\TEMP\Compression\myzip.zip"
    
        'Open the zip file if it exists, else create a new one
         Dim zip As Package = ZipPackage.Open(zipPath, _
              IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)
    
        'Add as many files as you like:
        AddToArchive(zip, "C:\TEMP\Compression\Compress Me1.txt")
        AddToArchive(zip, "C:\TEMP\Compression\Compress Me2.txt")
        AddToArchive(zip, "C:\TEMP\Compression\Compress Me3.txt")
    
        zip.Close() 'Close the zip file
    
    End Sub
    
    
    Private Sub AddToArchive(ByVal zip As Package, _
                         ByVal fileToAdd As String)
    
        'Replace spaces with an underscore (_)
        Dim uriFileName As String = fileToAdd.Replace(" ", "_")
    
        'A Uri always starts with a forward slash "/"
        Dim zipUri As String = String.Concat("/", _
                   IO.Path.GetFileName(uriFileName))
    
        Dim partUri As New Uri(zipUri, UriKind.Relative)
        Dim contentType As String = _
                   Net.Mime.MediaTypeNames.Application.Zip
    
        'The PackagePart contains the information:
        ' Where to extract the file when it's extracted (partUri)
        ' The type of content stream (MIME type):  (contentType)
        ' The type of compression:  (CompressionOption.Normal)
        Dim pkgPart As PackagePart = zip.CreatePart(partUri, _
                   contentType, CompressionOption.Normal)
    
        'Read all of the bytes from the file to add to the zip file
        Dim bites As Byte() = File.ReadAllBytes(fileToAdd)
    
        'Compress and write the bytes to the zip file
        pkgPart.GetStream().Write(bites, 0, bites.Length)
    
    End Sub
    

Points of Interest

Something you'll notice, if you open the .zip file with WinZip or some other zip utility, is a "[Content_Types].xml" file. Unfortunately, you have no control over the presence of this file. It is a file that includes content information about the types of file that are included in the zip file, such as "txt" for a Text File, or "doc" for a Word Document, etc.

Additionally, if you set any of the properties for the PackagePart (pkgPart.Package.PackageProperties), then you will have additional files included in the zip archive, such as a "###.psmdcp" file (where ### is a randomly generated number), which is a file containing metadata for the package properties; and an ".rels" file, which is an xml file containing meta-data about package relationships.

I've included an entire Zip Demo for you that demonstrates zipping and unzipping zip archives in VB.Net 2008. It's style is similar to WinZip, but not quite as full featured.

I hope it's helpful to you!

VBRocks
2008 MS Visual Basic MVP

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DataPrint, LLC
United States United States

Comments and Discussions

 
QuestionCompressed files on a network drive Pin
Member 865413517-Oct-12 22:13
Member 865413517-Oct-12 22:13 
AnswerRe: Compressed files on a network drive Pin
CS Rocks18-Oct-12 8:40
CS Rocks18-Oct-12 8:40 
QuestionError in Code Pin
Member 82011138-Aug-12 12:33
Member 82011138-Aug-12 12:33 
GeneralMy vote of 5 Pin
Gun Gun Febrianza8-Feb-12 16:00
Gun Gun Febrianza8-Feb-12 16:00 
GeneralMy vote of 5 Pin
Aces11728-Jun-11 10:43
Aces11728-Jun-11 10:43 
QuestionHow do you deal with huge files? Pin
Issac Peña26-May-11 4:10
Issac Peña26-May-11 4:10 
AnswerRe: How do you deal with huge files? Pin
Logi Guna18-Jan-13 5:24
professionalLogi Guna18-Jan-13 5:24 
GeneralMy vote of 2 Pin
mr200114-Jan-11 9:11
mr200114-Jan-11 9:11 
GeneralZIP file size much bigger than actual (unzipped) file Pin
mr200114-Jan-11 8:04
mr200114-Jan-11 8:04 
GeneralRe: ZIP file size much bigger than actual (unzipped) file Pin
mr200114-Jan-11 9:06
mr200114-Jan-11 9:06 
GeneralAdd passwor on zip file for secutiry concerns. Pin
xay0820106-Aug-10 7:50
xay0820106-Aug-10 7:50 
GeneralRe: Add passwor on zip file for secutiry concerns. Pin
Joy George K7-Oct-14 14:03
professionalJoy George K7-Oct-14 14:03 
GeneralConflicting Licence Pin
Bill960311-Apr-10 9:01
Bill960311-Apr-10 9:01 
GeneralRe: Conflicting Licence Pin
CS Rocks13-Apr-10 6:21
CS Rocks13-Apr-10 6:21 
QuestionNeed help with PackageProperties Pin
kommand10-Aug-09 4:23
kommand10-Aug-09 4:23 
QuestionHow to do this using .Net Framework 2 Pin
A N Saraf26-Jun-09 0:03
A N Saraf26-Jun-09 0:03 
AnswerRe: How to do this using .Net Framework 2 Pin
djhenrya23-Jan-12 1:45
djhenrya23-Jan-12 1:45 
Generalgood article Pin
Donsw8-May-09 7:37
Donsw8-May-09 7:37 
Questionremove [Content_Types].xml ??? Pin
Tibor.bl1-Apr-09 2:55
Tibor.bl1-Apr-09 2:55 
AnswerRe: remove [Content_Types].xml ??? Pin
J-Fix1-Apr-09 4:54
J-Fix1-Apr-09 4:54 
GeneralFile size Pin
Member 165484123-Mar-09 0:03
Member 165484123-Mar-09 0:03 
GeneralZIP library for VB.NET Pin
Cheeso22-Feb-09 8:55
Cheeso22-Feb-09 8:55 
QuestionCan't open zip files... Pin
Nick Rioux28-Aug-08 1:30
Nick Rioux28-Aug-08 1:30 
GeneralCongrates Pin
Rupesh Kumar Swami25-Aug-08 19:53
Rupesh Kumar Swami25-Aug-08 19:53 
GeneralCongratulation PinPopular
Abhijit Jana25-Aug-08 16:55
professionalAbhijit Jana25-Aug-08 16:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.