Show / Hide Table of Contents

Class DeflateStream

A class for compressing and decompressing streams using the Deflate algorithm.

Inheritance
System.Object
System.MarshalByRefObject
System.IO.Stream
DeflateStream
Implements
System.IAsyncDisposable
System.IDisposable
Inherited Members
System.IO.Stream.Null
System.IO.Stream.BeginRead(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object)
System.IO.Stream.BeginWrite(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object)
System.IO.Stream.Close()
System.IO.Stream.CopyTo(System.IO.Stream)
System.IO.Stream.CopyTo(System.IO.Stream, System.Int32)
System.IO.Stream.CopyToAsync(System.IO.Stream)
System.IO.Stream.CopyToAsync(System.IO.Stream, System.Int32)
System.IO.Stream.CopyToAsync(System.IO.Stream, System.Int32, System.Threading.CancellationToken)
System.IO.Stream.CopyToAsync(System.IO.Stream, System.Threading.CancellationToken)
System.IO.Stream.CreateWaitHandle()
System.IO.Stream.Dispose()
System.IO.Stream.DisposeAsync()
System.IO.Stream.EndRead(System.IAsyncResult)
System.IO.Stream.EndWrite(System.IAsyncResult)
System.IO.Stream.FlushAsync()
System.IO.Stream.FlushAsync(System.Threading.CancellationToken)
System.IO.Stream.ObjectInvariant()
System.IO.Stream.Read(System.Span<System.Byte>)
System.IO.Stream.ReadAsync(System.Byte[], System.Int32, System.Int32)
System.IO.Stream.ReadAsync(System.Byte[], System.Int32, System.Int32, System.Threading.CancellationToken)
System.IO.Stream.ReadAsync(System.Memory<System.Byte>, System.Threading.CancellationToken)
System.IO.Stream.ReadByte()
System.IO.Stream.Synchronized(System.IO.Stream)
System.IO.Stream.ValidateBufferArguments(System.Byte[], System.Int32, System.Int32)
System.IO.Stream.ValidateCopyToArguments(System.IO.Stream, System.Int32)
System.IO.Stream.Write(System.ReadOnlySpan<System.Byte>)
System.IO.Stream.WriteAsync(System.Byte[], System.Int32, System.Int32)
System.IO.Stream.WriteAsync(System.Byte[], System.Int32, System.Int32, System.Threading.CancellationToken)
System.IO.Stream.WriteAsync(System.ReadOnlyMemory<System.Byte>, System.Threading.CancellationToken)
System.IO.Stream.WriteByte(System.Byte)
System.IO.Stream.CanTimeout
System.IO.Stream.ReadTimeout
System.IO.Stream.WriteTimeout
System.MarshalByRefObject.GetLifetimeService()
System.MarshalByRefObject.InitializeLifetimeService()
System.MarshalByRefObject.MemberwiseClone(System.Boolean)
System.Object.Equals(System.Object)
System.Object.Equals(System.Object, System.Object)
System.Object.GetHashCode()
System.Object.GetType()
System.Object.MemberwiseClone()
System.Object.ReferenceEquals(System.Object, System.Object)
System.Object.ToString()
Namespace: OfficeOpenXml.Packaging.Ionic.Zlib
Assembly: EPPlus.dll
Syntax
public class DeflateStream : Stream, IAsyncDisposable, IDisposable
Remarks

The DeflateStream is a Decorator on a System.IO.Stream. It adds DEFLATE 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 DEFLATE, which is documented in IETF RFC 1951, "DEFLATE Compressed Data Format Specification version 1.3.".

This class is similar to ZlibStream, except that ZlibStream adds the RFC 1950 - ZLIB framing bytes to a compressed stream when compressing, or expects the RFC1950 framing bytes when decompressing. The DeflateStream does not.

Constructors

DeflateStream(Stream, CompressionMode)

Create a DeflateStream using the specified CompressionMode.

Declaration
public DeflateStream(Stream stream, CompressionMode mode)
Parameters
Type Name Description
System.IO.Stream stream

The stream which will be read or written.

CompressionMode mode

Indicates whether the DeflateStream will compress or decompress.

Remarks

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

Examples

This example uses a DeflateStream 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 + ".deflated"))
    {
        using (Stream compressor = new DeflateStream(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 & ".deflated")
        Using compressor As Stream = New DeflateStream(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

DeflateStream(Stream, CompressionMode, CompressionLevel)

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

Declaration
public DeflateStream(Stream stream, CompressionMode mode, CompressionLevel level)
Parameters
Type Name Description
System.IO.Stream stream

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

CompressionMode mode

Indicates whether the DeflateStream will compress or decompress.

CompressionLevel level

A tuning knob to trade speed for effectiveness.

Remarks

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

Examples

This example uses a DeflateStream 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 + ".deflated"))
    {
        using (Stream compressor = new DeflateStream(raw,
                                                     CompressionMode.Compress,
                                                     CompressionLevel.BestCompression))
        {
            byte[] buffer = new byte[WORKING_BUFFER_SIZE];
            int n= -1;
            while (n != 0)
            {
                if (n > 0)
                    compressor.Write(buffer, 0, n);
                n= input.Read(buffer, 0, buffer.Length);
            }
        }
    }
}
Using input As Stream = File.OpenRead(fileToCompress)
    Using raw As FileStream = File.Create(fileToCompress & ".deflated")
        Using compressor As Stream = New DeflateStream(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

DeflateStream(Stream, CompressionMode, CompressionLevel, Boolean)

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

Declaration
public DeflateStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
Parameters
Type Name Description
System.IO.Stream stream

The stream which will be read or written.

CompressionMode mode

Indicates whether the DeflateStream will compress or decompress.

CompressionLevel level

A tuning knob to trade speed for effectiveness.

System.Boolean leaveOpen

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

Remarks

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

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 System.IO.MemoryStream that will be re-read after compression. Specify true for the leaveOpen parameter to leave the stream open.

Examples

This example shows how to use a DeflateStream to compress data from a file, and store the compressed data into another file.

using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
{
    using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
    {
        using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
        {
            byte[] buffer = new byte[WORKING_BUFFER_SIZE];
            int n= -1;
            while (n != 0)
            {
                if (n > 0)
                    compressor.Write(buffer, 0, n);
                n= input.Read(buffer, 0, buffer.Length);
            }
        }
    }
    // can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".deflated")
    Using input As Stream = File.OpenRead(fileToCompress)
        Using compressor As Stream = New DeflateStream(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

DeflateStream(Stream, CompressionMode, Boolean)

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

Declaration
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen)
Parameters
Type Name Description
System.IO.Stream stream

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

CompressionMode mode

Indicates whether the DeflateStream will compress or decompress.

System.Boolean leaveOpen

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

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 memory stream that will be re-read after compression. Specify true for the leaveOpen parameter to leave the stream open.

The DeflateStream will use the default compression level.

See the other overloads of this constructor for example code.

Properties

BufferSize

The size of the working buffer for the compression codec.

Declaration
public int BufferSize { get; set; }
Property Value
Type Description
System.Int32
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.

Declaration
public override bool CanRead { get; }
Property Value
Type Description
System.Boolean
Overrides
System.IO.Stream.CanRead
Remarks

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

CanSeek

Indicates whether the stream supports Seek operations.

Declaration
public override bool CanSeek { get; }
Property Value
Type Description
System.Boolean
Overrides
System.IO.Stream.CanSeek
Remarks

Always returns false.

CanWrite

Indicates whether the stream can be written.

Declaration
public override bool CanWrite { get; }
Property Value
Type Description
System.Boolean
Overrides
System.IO.Stream.CanWrite
Remarks

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

FlushMode

This property sets the flush behavior on the stream.

Declaration
public virtual FlushType FlushMode { get; set; }
Property Value
Type Description
FlushType
Remarks

See the ZLIB documentation for the meaning of the flush behavior.

Length

Reading this property always throws a System.NotImplementedException.

Declaration
public override long Length { get; }
Property Value
Type Description
System.Int64
Overrides
System.IO.Stream.Length

Position

The position of the stream pointer.

Declaration
public override long Position { get; set; }
Property Value
Type Description
System.Int64
Overrides
System.IO.Stream.Position
Remarks

Setting this property always throws a System.NotImplementedException. 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.

Strategy

The ZLIB strategy to be used during compression.

Declaration
public CompressionStrategy Strategy { get; set; }
Property Value
Type Description
CompressionStrategy
Remarks

By tweaking this parameter, you may be able to optimize the compression for data with particular characteristics.

TotalIn

Returns the total number of bytes input so far.

Declaration
public virtual long TotalIn { get; }
Property Value
Type Description
System.Int64

TotalOut

Returns the total number of bytes output so far.

Declaration
public virtual long TotalOut { get; }
Property Value
Type Description
System.Int64

Methods

CompressBuffer(Byte[])

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

Declaration
public static byte[] CompressBuffer(byte[] b)
Parameters
Type Name Description
System.Byte[] b

A buffer to compress.

Returns
Type Description
System.Byte[]

The data in compressed form

Remarks

Uncompress it with UncompressBuffer(Byte[]).

See Also
CompressString(String)
UncompressBuffer(Byte[])
CompressBuffer(Byte[])
CompressBuffer(Byte[])

CompressString(String)

Compress a string into a byte array using DEFLATE (RFC 1951).

Declaration
public static byte[] CompressString(string s)
Parameters
Type Name Description
System.String s

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

Returns
Type Description
System.Byte[]

The string in compressed form

Remarks

Uncompress it with UncompressString(Byte[]).

See Also
UncompressString(Byte[])
CompressBuffer(Byte[])
CompressString(String)
CompressString(String)

Dispose(Boolean)

Dispose the stream.

Declaration
protected override void Dispose(bool disposing)
Parameters
Type Name Description
System.Boolean disposing

true if the Dispose method was invoked by user code.

Overrides
System.IO.Stream.Dispose(System.Boolean)
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.

Application code won't call this code directly. 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.

Declaration
public override void Flush()
Overrides
System.IO.Stream.Flush()

Read(Byte[], Int32, Int32)

Read data from the stream.

Declaration
public override int Read(byte[] buffer, int offset, int count)
Parameters
Type Name Description
System.Byte[] buffer

The buffer into which the read data should be placed.

System.Int32 offset

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

System.Int32 count

the number of bytes to read.

Returns
Type Description
System.Int32

the number of bytes actually read

Overrides
System.IO.Stream.Read(System.Byte[], System.Int32, System.Int32)
Remarks

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

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

Seek(Int64, SeekOrigin)

Calling this method always throws a System.NotImplementedException.

Declaration
public override long Seek(long offset, SeekOrigin origin)
Parameters
Type Name Description
System.Int64 offset

this is irrelevant, since it will always throw!

System.IO.SeekOrigin origin

this is irrelevant, since it will always throw!

Returns
Type Description
System.Int64

irrelevant!

Overrides
System.IO.Stream.Seek(System.Int64, System.IO.SeekOrigin)

SetLength(Int64)

Calling this method always throws a System.NotImplementedException.

Declaration
public override void SetLength(long value)
Parameters
Type Name Description
System.Int64 value

this is irrelevant, since it will always throw!

Overrides
System.IO.Stream.SetLength(System.Int64)

UncompressBuffer(Byte[])

Uncompress a DEFLATE'd byte array into a byte array.

Declaration
public static byte[] UncompressBuffer(byte[] compressed)
Parameters
Type Name Description
System.Byte[] compressed

A buffer containing data that has been compressed with DEFLATE.

Returns
Type Description
System.Byte[]

The data in uncompressed form

See Also
CompressBuffer(Byte[])
UncompressString(Byte[])
UncompressBuffer(Byte[])
UncompressBuffer(Byte[])

UncompressString(Byte[])

Uncompress a DEFLATE'd byte array into a single string.

Declaration
public static string UncompressString(byte[] compressed)
Parameters
Type Name Description
System.Byte[] compressed

A buffer containing DEFLATE-compressed data.

Returns
Type Description
System.String

The uncompressed string

See Also
CompressString(String)
UncompressBuffer(Byte[])
UncompressString(Byte[])
UncompressString(Byte[])

Write(Byte[], Int32, Int32)

Write data to the stream.

Declaration
public override void Write(byte[] buffer, int offset, int count)
Parameters
Type Name Description
System.Byte[] buffer

The buffer holding data to write to the stream.

System.Int32 offset

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

System.Int32 count

the number of bytes to write.

Overrides
System.IO.Stream.Write(System.Byte[], System.Int32, System.Int32)
Remarks

If you wish to use the DeflateStream to compress data while writing, you can create a DeflateStream with CompressionMode.Compress, and a writable output stream. Then call Write() on that DeflateStream, 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 DeflateStream to decompress data while writing, you can create a DeflateStream 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 DeflateStream can be used for Read() or Write(), but not both.

Implements

System.IAsyncDisposable
System.IDisposable

See Also

ZlibStream
GZipStream
In This Article
Back to top Generated by DocFX