Click here to Skip to main content
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 PinmemberMember 865413517-Oct-12 23:13 
AnswerRe: Compressed files on a network drive PinmemberVB Rocks18-Oct-12 9:40 
QuestionError in Code PinmemberMember 82011138-Aug-12 13:33 
GeneralMy vote of 5 Pinmemberhazekaizer8-Feb-12 17:00 
GeneralMy vote of 5 PinmemberAces11728-Jun-11 11:43 
QuestionHow do you deal with huge files? PinmemberIssac Peña26-May-11 5:10 
AnswerRe: How do you deal with huge files? PinmemberLogi Guna18-Jan-13 6:24 
GeneralMy vote of 2 Pinmembermr200114-Jan-11 10:11 
GeneralZIP file size much bigger than actual (unzipped) file Pinmembermr200114-Jan-11 9:04 
GeneralRe: ZIP file size much bigger than actual (unzipped) file Pinmembermr200114-Jan-11 10:06 
GeneralAdd passwor on zip file for secutiry concerns. Pinmemberxay0820106-Aug-10 8:50 
GeneralRe: Add passwor on zip file for secutiry concerns. PinmemberJoy George K7-Oct-14 15:03 
GeneralConflicting Licence PinmemberBill960311-Apr-10 10:01 
GeneralRe: Conflicting Licence PinmemberVB Rocks13-Apr-10 7:21 
QuestionNeed help with PackageProperties Pinmemberkommand10-Aug-09 5:23 
QuestionHow to do this using .Net Framework 2 PinmemberAmit N. Saraf26-Jun-09 1:03 
AnswerRe: How to do this using .Net Framework 2 Pinmemberdjhenrya23-Jan-12 2:45 
Generalgood article PinmemberDonsw8-May-09 8:37 
Questionremove [Content_Types].xml ??? PinmemberTibor.bl1-Apr-09 3:55 
AnswerRe: remove [Content_Types].xml ??? PinmemberJ-Fix1-Apr-09 5:54 
GeneralFile size PinmemberMember 165484123-Mar-09 1:03 
GeneralZIP library for VB.NET PinmemberCheeso22-Feb-09 9:55 
QuestionCan't open zip files... PinmemberNickr528-Aug-08 2:30 
GeneralCongrates PinmemberRupesh Kumar Swami25-Aug-08 20:53 
GeneralCongratulation PinmemberAbhijit 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
Web01 | 2.8.1411022.1 | Last Updated 25 Jul 2008
Article Copyright 2008 by CS Rocks
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid