Click here to Skip to main content
11,412,834 members (75,128 online)
Click here to Skip to main content

Zip Files Easy!

, 25 Jul 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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:
        Imports System.IO.Packaging
  • Write some code:

        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:

        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)

Share

About the Author

CS Rocks
Software Developer DataPrint, LLC
United States United States

Comments and Discussions

 
QuestionCompressed files on a network drive Pin
Member 8654135 at 17-Oct-12 23:13
memberMember 865413517-Oct-12 23:13 
AnswerRe: Compressed files on a network drive Pin
VB Rocks at 18-Oct-12 9:40
memberVB Rocks18-Oct-12 9:40 
QuestionError in Code Pin
Member 8201113 at 8-Aug-12 13:33
memberMember 82011138-Aug-12 13:33 
GeneralMy vote of 5 Pin
hazekaizer at 8-Feb-12 17:00
memberhazekaizer8-Feb-12 17:00 
GeneralMy vote of 5 Pin
Aces117 at 28-Jun-11 11:43
memberAces11728-Jun-11 11:43 
QuestionHow do you deal with huge files? Pin
Issac Peña at 26-May-11 5:10
memberIssac Peña26-May-11 5:10 
AnswerRe: How do you deal with huge files? Pin
Logi Guna at 18-Jan-13 6:24
memberLogi Guna18-Jan-13 6:24 
GeneralMy vote of 2 Pin
mr2001 at 14-Jan-11 10:11
membermr200114-Jan-11 10:11 
GeneralZIP file size much bigger than actual (unzipped) file Pin
mr2001 at 14-Jan-11 9:04
membermr200114-Jan-11 9:04 
GeneralRe: ZIP file size much bigger than actual (unzipped) file Pin
mr2001 at 14-Jan-11 10:06
membermr200114-Jan-11 10:06 
GeneralAdd passwor on zip file for secutiry concerns. Pin
xay082010 at 6-Aug-10 8:50
memberxay0820106-Aug-10 8:50 
GeneralRe: Add passwor on zip file for secutiry concerns. Pin
Joy George K at 7-Oct-14 15:03
memberJoy George K7-Oct-14 15:03 
GeneralConflicting Licence Pin
Bill9603 at 11-Apr-10 10:01
memberBill960311-Apr-10 10:01 
GeneralRe: Conflicting Licence Pin
VB Rocks at 13-Apr-10 7:21
memberVB Rocks13-Apr-10 7:21 
QuestionNeed help with PackageProperties Pin
kommand at 10-Aug-09 5:23
memberkommand10-Aug-09 5:23 
QuestionHow to do this using .Net Framework 2 Pin
Amit N. Saraf at 26-Jun-09 1:03
memberAmit N. Saraf26-Jun-09 1:03 
AnswerRe: How to do this using .Net Framework 2 Pin
djhenrya at 23-Jan-12 2:45
memberdjhenrya23-Jan-12 2:45 
Generalgood article Pin
Donsw at 8-May-09 8:37
memberDonsw8-May-09 8:37 
Questionremove [Content_Types].xml ??? Pin
Tibor.bl at 1-Apr-09 3:55
memberTibor.bl1-Apr-09 3:55 
AnswerRe: remove [Content_Types].xml ??? Pin
J-Fix at 1-Apr-09 5:54
memberJ-Fix1-Apr-09 5:54 
GeneralFile size Pin
Member 1654841 at 23-Mar-09 1:03
memberMember 165484123-Mar-09 1:03 
GeneralZIP library for VB.NET Pin
Cheeso at 22-Feb-09 9:55
memberCheeso22-Feb-09 9:55 
QuestionCan't open zip files... Pin
Nickr5 at 28-Aug-08 2:30
memberNickr528-Aug-08 2:30 
GeneralCongrates Pin
Rupesh Kumar Swami at 25-Aug-08 20:53
memberRupesh Kumar Swami25-Aug-08 20:53 
GeneralCongratulation Pin
Abhijit Jana at 25-Aug-08 17:55
memberAbhijit Jana25-Aug-08 17:55 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150427.1 | Last Updated 25 Jul 2008
Article Copyright 2008 by CS Rocks
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid