Click here to Skip to main content
Licence CPOL
First Posted 25 Jul 2008
Views 65,043
Downloads 3,093
Bookmarked 82 times

Zip Files Easy!

By | 25 Jul 2008 | Article
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.
Prize winner in Competition "Best VB.NET article of July 2008"

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)

About the Author

VB Rocks

Software Developer
DataPrint, LLC
United States United States

Member

My blog: http://www.garylima.blogspot.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmemberhazekaizer16:00 8 Feb '12  
GeneralMy vote of 5 PinmemberAces11710:43 28 Jun '11  
QuestionHow do you deal with huge files? PinmemberIssac Peña4:10 26 May '11  
GeneralMy vote of 2 Pinmembermr20019:11 14 Jan '11  
GeneralZIP file size much bigger than actual (unzipped) file Pinmembermr20018:04 14 Jan '11  
GeneralRe: ZIP file size much bigger than actual (unzipped) file Pinmembermr20019:06 14 Jan '11  
GeneralAdd passwor on zip file for secutiry concerns. Pinmemberxay0820107:50 6 Aug '10  
GeneralConflicting Licence PinmemberBill96039:01 11 Apr '10  
GeneralRe: Conflicting Licence PinmemberVB Rocks6:21 13 Apr '10  
QuestionNeed help with PackageProperties Pinmemberkommand4:23 10 Aug '09  
QuestionHow to do this using .Net Framework 2 PinmemberAmit N. Saraf0:03 26 Jun '09  
AnswerRe: How to do this using .Net Framework 2 Pinmemberdjhenrya1:45 23 Jan '12  
Generalgood article PinmemberDonsw7:37 8 May '09  
Questionremove [Content_Types].xml ??? PinmemberTibor.bl2:55 1 Apr '09  
AnswerRe: remove [Content_Types].xml ??? PinmemberJ-Fix4:54 1 Apr '09  
I've got the same problem, wanna use this stuff commercial, so this ballast file isn't acceptable... Does someone know if it's possible in any form to avoid the creating of this file?
GeneralFile size PinmemberMember 16548410:03 23 Mar '09  
GeneralZIP library for VB.NET PinmemberCheeso8:55 22 Feb '09  
QuestionCan't open zip files... PinmemberNickr51:30 28 Aug '08  
GeneralCongrates PinmemberRupesh Kumar Swami19:53 25 Aug '08  
GeneralCongratulation PinmemberAbhijit Jana16:55 25 Aug '08  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120604.1 | Last Updated 25 Jul 2008
Article Copyright 2008 by VB Rocks
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid