article

Zip Files Easy!

Email
Submitted on: 1/5/2015 3:45:00 PM
By: VBRocks (from psc cd)  
Level: Intermediate
User Rating: By 2 Users
Compatibility: VB.NET
Views: 3394
 
     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

This article has accompanying files

 
				

 
Zip Files Demo 
VB.Net 2008


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 System.IO.Packaging namespace and a few lines of code, you can easily create .zip archives with as many files as you like!


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


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 metadata 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

www.VisualBasicRocks.com




winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com


Other 5 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.