Compress and Decompress Data
Even with the ever-increasing capacity of hard drives and
the falling price of computer memory, it still pays to save space. In
.NET 2.0, a new System.IO.Compression
namespace makes it easy for a VB 2005 programmer to compress data as she
writes it to a stream, and decompress data as she reads it from a
stream.
Note
Need to save space before you store data in a file or database? . NET 2.0 makes compression and decompression easy.
How do I do that?
The new System.IO.Compression
namespace introduces two new stream classes: GZipStream
and DeflateStream
, which, as you'd guess, are
used to compress and decompress streams of data.
The algorithms used by these classes are lossless, which means that when you compress and decompress your data, you won't lose any information.
To use compression, you need to understand that a compression
stream wraps another stream. For example, if you
want to write some compressed data to a file, you first create a
FileStream
for the file. Then, you
wrap the FileStream
with the
GZipStream
or DeflateStream
. Here's how it works:
Dim fsWrite As New FileStream(FileName, FileMode.Create) Dim CompressStream As New GZipStream(fsWrite, CompressionMode.Compress)
Now, if you want to write data to the file, you use the GZipStream
. The GZipStream
compresses that data, and then
writes the compressed data to the wrapped FileStream
, which then writes it to the
underlying file. If you skip this process and write directly to the
FileStream
, you'll ...
Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.