Table of Contents

Class ZlibStream

Namespace
Ionic.Zlib
Assembly
SunamoDotNetZip.dll

Represents a Zlib stream for compression or decompression.

public class ZlibStream : Stream, IAsyncDisposable, IDisposable
Inheritance
ZlibStream
Implements
Inherited Members
Extension Methods

Remarks

The ZlibStream is a Decorator on a Stream. It adds ZLIB compression or decompression to any stream.

Using this stream, applications can compress or decompress data via stream Read() and Write() operations. Either compresssion or decompression can occur through either reading or writing. The compression format used is ZLIB, which is documented in IETF RFC 1950, "ZLIB Compressed Data Format Specification version 3.3". This implementation of ZLIB always uses DEFLATE as the compression method. (see IETF RFC 1951, "DEFLATE Compressed Data Format Specification version 1.3.")

The ZLIB format allows for varying compression methods, window sizes, and dictionaries. This implementation always uses the DEFLATE compression method, a preset dictionary, and 15 window bits by default.

This class is similar to DeflateStream, except that it adds the RFC1950 header and trailer bytes to a compressed stream when compressing, or expects the RFC1950 header and trailer bytes when decompressing. It is also similar to the GZipStream.

Constructors

ZlibStream(Stream, CompressionMode)

Create a ZlibStream using the specified CompressionMode.

public ZlibStream(Stream stream, CompressionMode mode)

Parameters

stream Stream

The stream which will be read or written.

mode CompressionMode

Indicates whether the ZlibStream will compress or decompress.

Examples

This example uses a ZlibStream to compress a file, and writes the compressed data to another file.

using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
    using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
    {
        using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
        {
            byte[] buffer = new byte[WORKING_BUFFER_SIZE];
            int n;
            while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
            {
                compressor.Write(buffer, 0, n);
            }
        }
    }
}
Using input As Stream = File.OpenRead(fileToCompress)
    Using raw As FileStream = File.Create(fileToCompress & ".zlib")
    Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
        Dim buffer As Byte() = New Byte(4096) {}
        Dim n As Integer = -1
        Do While (n <> 0)
            If (n > 0) Then
                compressor.Write(buffer, 0, n)
            End If
            n = input.Read(buffer, 0, buffer.Length)
        Loop
    End Using
    End Using
End Using

Remarks

When mode is CompressionMode.Compress, the ZlibStream will use the default compression level. The "captive" stream will be closed when the ZlibStream is closed.

ZlibStream(Stream, CompressionMode, CompressionLevel)

Create a ZlibStream using the specified CompressionMode and the specified CompressionLevel.

public ZlibStream(Stream stream, CompressionMode mode, CompressionLevel level)

Parameters

stream Stream

The stream to be read or written while deflating or inflating.

mode CompressionMode

Indicates whether the ZlibStream will compress or decompress.

level CompressionLevel

A tuning knob to trade speed for effectiveness.

Examples

This example uses a ZlibStream to compress data from a file, and writes the compressed data to another file.

using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
    using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
    {
        using (Stream compressor = new ZlibStream(raw,
                                                  CompressionMode.Compress,
                                                  CompressionLevel.BestCompression))
        {
            byte[] buffer = new byte[WORKING_BUFFER_SIZE];
            int n;
            while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
            {
                compressor.Write(buffer, 0, n);
            }
        }
    }
}
Using input As Stream = File.OpenRead(fileToCompress)
    Using raw As FileStream = File.Create(fileToCompress & ".zlib")
        Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
            Dim buffer As Byte() = New Byte(4096) {}
            Dim n As Integer = -1
            Do While (n <> 0)
                If (n > 0) Then
                    compressor.Write(buffer, 0, n)
                End If
                n = input.Read(buffer, 0, buffer.Length)
            Loop
        End Using
    End Using
End Using

Remarks

When mode is CompressionMode.Decompress, the level parameter is ignored. The "captive" stream will be closed when the ZlibStream is closed.

ZlibStream(Stream, CompressionMode, CompressionLevel, bool)

Create a ZlibStream using the specified CompressionMode and the specified CompressionLevel, and explicitly specify whether the stream should be left open after Deflation or Inflation.

public ZlibStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)

Parameters

stream Stream

The stream which will be read or written.

mode CompressionMode

Indicates whether the ZlibStream will compress or decompress.

level CompressionLevel

A tuning knob to trade speed for effectiveness. This parameter is effective only when mode is CompressionMode.Compress.

leaveOpen bool

true if the application would like the stream to remain open after inflation/deflation.

Examples

This example shows how to use a ZlibStream to compress the data from a file, and store the result into another file. The filestream remains open to allow additional data to be written to it.

using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
{
    using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
    {
        using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
        {
            byte[] buffer = new byte[WORKING_BUFFER_SIZE];
            int n;
            while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
            {
                compressor.Write(buffer, 0, n);
            }
        }
    }
    // can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".zlib")
    Using input As Stream = File.OpenRead(fileToCompress)
        Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
            Dim buffer As Byte() = New Byte(4096) {}
            Dim n As Integer = -1
            Do While (n <> 0)
                If (n > 0) Then
                    compressor.Write(buffer, 0, n)
                End If
                n = input.Read(buffer, 0, buffer.Length)
            Loop
        End Using
    End Using
    ' can write additional data to the output stream here.
End Using

Remarks

This constructor allows the application to request that the captive stream remain open after the deflation or inflation occurs. By default, after Close() is called on the stream, the captive stream is also closed. In some cases this is not desired, for example if the stream is a MemoryStream that will be re-read after compression. Specify true for the leaveOpen parameter to leave the stream open.

When mode is CompressionMode.Decompress, the level parameter is ignored.

ZlibStream(Stream, CompressionMode, bool)

Create a ZlibStream using the specified CompressionMode, and explicitly specify whether the captive stream should be left open after Deflation or Inflation.

public ZlibStream(Stream stream, CompressionMode mode, bool leaveOpen)

Parameters

stream Stream

The stream which will be read or written. This is called the "captive" stream in other places in this documentation.

mode CompressionMode

Indicates whether the ZlibStream will compress or decompress.

leaveOpen bool

true if the application would like the stream to remain open after inflation/deflation.

Remarks

When mode is CompressionMode.Compress, the ZlibStream will use the default compression level.

This constructor allows the application to request that the captive stream remain open after the deflation or inflation occurs. By default, after Close() is called on the stream, the captive stream is also closed. In some cases this is not desired, for example if the stream is a MemoryStream that will be re-read after compression. Specify true for the leaveOpen parameter to leave the stream open.

See the other overloads of this constructor for example code.

Properties

BufferSize

The size of the working buffer for the compression codec.

public int BufferSize { get; set; }

Property Value

int

Remarks

The working buffer is used for all stream operations. The default size is 1024 bytes. The minimum size is 128 bytes. You may get better performance with a larger buffer. Then again, you might not. You would have to test it.

Set this before the first call to Read() or Write() on the stream. If you try to set it afterwards, it will throw.

CanRead

Indicates whether the stream can be read.

public override bool CanRead { get; }

Property Value

bool

Remarks

The return value depends on whether the captive stream supports reading.

CanSeek

Indicates whether the stream supports Seek operations.

public override bool CanSeek { get; }

Property Value

bool

Remarks

Always returns false.

CanWrite

Indicates whether the stream can be written.

public override bool CanWrite { get; }

Property Value

bool

Remarks

The return value depends on whether the captive stream supports writing.

FlushMode

This property sets the flush behavior on the stream. Sorry, though, not sure exactly how to describe all the various settings.

public virtual FlushType FlushMode { get; set; }

Property Value

FlushType

Length

Reading this property always throws a NotSupportedException.

public override long Length { get; }

Property Value

long

Position

The position of the stream pointer.

public override long Position { get; set; }

Property Value

long

Remarks

Setting this property always throws a NotSupportedException. Reading will return the total bytes written out, if used in writing, or the total bytes read in, if used in reading. The count may refer to compressed bytes or uncompressed bytes, depending on how you've used the stream.

TotalIn

Returns the total number of bytes input so far.

public virtual long TotalIn { get; }

Property Value

long

TotalOut

Returns the total number of bytes output so far.

public virtual long TotalOut { get; }

Property Value

long

Methods

CompressBuffer(byte[])

Compress a byte array into a new byte array using ZLIB.

public static byte[] CompressBuffer(byte[] buffer)

Parameters

buffer byte[]

A buffer to compress.

Returns

byte[]

The data in compressed form

Remarks

Uncompress it with UncompressBuffer(byte[]).

See Also

CompressString(string)

Compress a string into a byte array using ZLIB.

public static byte[] CompressString(string text)

Parameters

text string

A string to compress. The string will first be encoded using UTF8, then compressed.

Returns

byte[]

The string in compressed form

Remarks

Uncompress it with UncompressString(byte[]).

See Also

Dispose(bool)

Dispose the stream.

protected override void Dispose(bool disposing)

Parameters

disposing bool

indicates whether the Dispose method was invoked by user code.

Remarks

This may or may not result in a Close() call on the captive stream. See the constructors that have a leaveOpen parameter for more information.

This method may be invoked in two distinct scenarios. If disposing == true, the method has been called directly or indirectly by a user's code, for example via the public Dispose() method. In this case, both managed and unmanaged resources can be referenced and disposed. If disposing == false, the method has been called by the runtime from inside the object finalizer and this method should not reference other objects; in that case only unmanaged resources must be referenced or disposed.

Flush()

Flush the stream.

public override void Flush()

Read(byte[], int, int)

Read data from the stream.

public override int Read(byte[] buffer, int offset, int count)

Parameters

buffer byte[]

The buffer into which the read data should be placed.

offset int

the offset within that data array to put the first byte read.

count int

the number of bytes to read.

Returns

int

the number of bytes read

Remarks

If you wish to use the ZlibStream to compress data while reading, you can create a ZlibStream with CompressionMode.Compress, providing an uncompressed data stream. Then call Read() on that ZlibStream, and the data read will be compressed. If you wish to use the ZlibStream to decompress data while reading, you can create a ZlibStream with CompressionMode.Decompress, providing a readable compressed data stream. Then call Read() on that ZlibStream, and the data will be decompressed as it is read.

A ZlibStream can be used for Read() or Write(), but not both.

Seek(long, SeekOrigin)

Calling this method always throws a NotSupportedException.

public override long Seek(long offset, SeekOrigin origin)

Parameters

offset long

The offset to seek to.... IF THIS METHOD ACTUALLY DID ANYTHING.

origin SeekOrigin

The reference specifying how to apply the offset.... IF THIS METHOD ACTUALLY DID ANYTHING.

Returns

long

nothing. This method always throws.

SetLength(long)

Calling this method always throws a NotSupportedException.

public override void SetLength(long value)

Parameters

value long

The new value for the stream length.... IF THIS METHOD ACTUALLY DID ANYTHING.

UncompressBuffer(byte[])

Uncompress a ZLIB-compressed byte array into a byte array.

public static byte[] UncompressBuffer(byte[] compressed)

Parameters

compressed byte[]

A buffer containing ZLIB-compressed data.

Returns

byte[]

The data in uncompressed form

See Also

UncompressString(byte[])

Uncompress a ZLIB-compressed byte array into a single string.

public static string UncompressString(byte[] compressed)

Parameters

compressed byte[]

A buffer containing ZLIB-compressed data.

Returns

string

The uncompressed string

See Also

Write(byte[], int, int)

Write data to the stream.

public override void Write(byte[] buffer, int offset, int count)

Parameters

buffer byte[]

The buffer holding data to write to the stream.

offset int

the offset within that data array to find the first byte to write.

count int

the number of bytes to write.

Remarks

If you wish to use the ZlibStream to compress data while writing, you can create a ZlibStream with CompressionMode.Compress, and a writable output stream. Then call Write() on that ZlibStream, providing uncompressed data as input. The data sent to the output stream will be the compressed form of the data written. If you wish to use the ZlibStream to decompress data while writing, you can create a ZlibStream with CompressionMode.Decompress, and a writable output stream. Then call Write() on that stream, providing previously compressed data. The data sent to the output stream will be the decompressed form of the data written.

A ZlibStream can be used for Read() or Write(), but not both.

See Also