.NET Tips and Tricks

Blog archive

Create .zip Files from Code

If you've ever wanted to create a .zip file from your application, the System.IO.Compression.GZipStream will let you do it, assuming that you're comfortable with your file being in the industry-standard .gzip format (though I'm told you can swap in other compression schemes).

For this tip, I'm assuming that the file is small enough that you can read it all in one gulp. In that scenario, my first move is to define a FileStream object for the file I want to compress, read the file into memory, and close the FileStream:

Dim unCompressedFile As FileStream
unCompressedFile = File.OpenRead("C:\GreatBigFile.txt")
Dim bytes(5000) As Byte
Dim bytesRead As Integer
bytesRead = unCompressedFile.Read(bytes, 0, 5000)
unCompressedFile.Close()

My next move is to create a FileStream object for the compressed file I want to create:

Dim CompressedFile As FileStream
CompressedFile = File.Create("C:\IttyBittyFile.gzip")

With all the files in place, I'm ready to create the GZipStream object that will do the actual compression. You have to pass two parameters when creating the GZipStream object: The first is the FileStream for the compressed file you intend to create; the second indicates that you want to compress the file.

Here's my code to create a compressed file called IttyBittyFile.gzip:

Dim zipper As GZipStream
zipper = New GZipStream(CompressedFile, CompressionMode.Compress)

Now I can use the GZipStream Write method to write out the compressed file, passing the bytes I retrieved from the original file:

zipper.Write(bytes, 0, bytesRead)

Finally, of course, I close the GZipStream object and my compressed file:

zipper.Close()
CompressedFile.Close()

As you probably suspect, if you change the CompressionMode and pass in a compressed file, you can use GZipStream to decompress a file.

Posted by Peter Vogel on 12/10/2015


comments powered by Disqus

Featured

Subscribe on YouTube