
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Compressing and Decompressing Your Files
|
749
12.28 Compressing and Decompressing Your Files
Problem
You need a way to compress the data you write to a file using one of the stream-
based classes. In addition, you need a way to decompress the data from this com-
pressed file when you read it back in.
Solution
Use the System.IO.Compression.DeflateStream or the System.IO.Compression.GZip-
Stream
classes to read and write compressed data to a file. The CompressFile,
DeCompressFile, and DeCompress methods shown in Example 12-16 demonstrate how
to use these classes to compress and expand data on the fly.
Example 12-16. The CompressFile, DeCompressFile, and DeCompress methods
public static void CompressFile(Stream strm, byte[] data,
CompressionType compressionType)
{
// Determine how to compress the file.
Stream deflate = null;
if (compressionType == CompressionType.Deflate)
{
using (deflate = new DeflateStream(strm, CompressionMode.Compress))
{
// Write compressed data to the file.
deflate.Write(data, 0, data.Length);
}
}
else
{
using (deflate = new GZipStream(strm, CompressionMode.Compress))
{
// Write compressed data to the file.
deflate.Write(data, 0, data.Length);
}
}
}
public static byte[] DeCompressFile(Stream strm,
CompressionType compressionType)
{
// Determine how to decompress the ...