This topic demonstrates how to compress data that is read from a System.IO.FileStream to a System.IO.MemoryStream using the GZipCompressedStream class.
Although we are using a FileStream as our source and a MemoryStream as our destination, we could have also used any other type of stream. For example, we could have compressed data read from a MemoryStream to another MemoryStream or to a FileStream.
To compress data that is read from a stream, the following steps must be taken:
Create the source stream from which the data will be read. For the purposes of this example, our source stream will be a System.IO.FileStream.
Create the destination stream to which the compressed data will be written. For the purposes of this example, our destination stream will be a System.IO.MemoryStream.
Create a GZipCompressedStream around the destination stream. For the purposes of this example we used the GZipCompressedStream class however we could have also used the XceedCompressedStream or the ZLibCompressedStream classes.
Read the data from the source System.IO.FileStream.
Write the compressed data to the destination System.IO.MemoryStream. Creating the GZipCompressedStream around the destination stream means that the data that is written to the destination System.IO.MemoryStream will be compressed as it is written.
The following example demonstrates how to read data from a System.IO.FileStream and compress it to a System.IO.MemoryStream using the GZipCompressedStream class.
VB.NET | ![]() |
---|---|
|
C# | ![]() |
---|---|
using System.IO; |
The main questions you should ask yourself when compressing data read from a stream are:
Do you want to prevent the inner stream from being closed when the GZipCompressedStream is closed? Set the Transient property of the GZipCompressedStream class to true.
Do you want to compress the data read from a stream using the Xceed or ZLib compression formats? Use the XceedCompressedStream or the ZLibCompressedStream classes instead of the GZipCompressedStream.
Do you want to compress data read from a stream but without a compression format (header/footer)? Use the CompressedStream class.
Do you only want a quick and easy way to compress a byte array? Use the static Compress method of the desired compression format class.