Show / Hide Table of Contents

Class GZipStream

A class for compressing and decompressing GZIP streams.

Inheritance
System.Object
System.MarshalByRefObject
System.IO.Stream
GZipStream
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 GZipStream : Stream, IAsyncDisposable, IDisposable
Remarks

The GZipStream is a Decorator on a System.IO.Stream. It adds GZIP compression or decompression to any stream.

Like the System.IO.Compression.GZipStream in the .NET Base Class Library, the Ionic.Zlib.GZipStream can compress while writing, or decompress while reading, but not vice versa. The compression method used is GZIP, which is documented in IETF RFC 1952, "GZIP file format specification version 4.3".

A GZipStream can be used to decompress data (through Read()) or to compress data (through Write()), but not both.

If you wish to use the GZipStream to compress data, you must wrap it around a write-able stream. As you call Write() on the GZipStream, the data will be compressed into the GZIP format. If you want to decompress data, you must wrap the GZipStream around a readable stream that contains an IETF RFC 1952-compliant stream. The data will be decompressed as you call Read() on the GZipStream.

Though the GZIP format allows data from multiple files to be concatenated together, this stream handles only a single segment of GZIP format, typically representing a single file.

This class is similar to ZlibStream and DeflateStream. ZlibStream handles RFC1950-compliant streams. DeflateStream handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.

Constructors

GZipStream(Stream, CompressionMode)

Create a GZipStream using the specified CompressionMode.

Declaration
public GZipStream(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 GZipStream will compress or decompress.

Remarks

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

As noted in the class documentation, the CompressionMode (Compress or Decompress) also establishes the "direction" of the stream. A GZipStream with CompressionMode.Compress works only through Write(). A GZipStream with CompressionMode.Decompress works only through Read().

Examples

This example shows how to use a GZipStream to compress data.

using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
    using (var raw = System.IO.File.Create(outputFile))
    {
        using (Stream compressor = new GZipStream(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);
            }
        }
    }
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
    Using raw As FileStream = File.Create(outputFile)
    Using compressor As Stream = New GZipStream(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

This example shows how to use a GZipStream to uncompress a file.

private void GunZipFile(string filename)
{
    if (!filename.EndsWith(".gz))
        throw new ArgumentException("filename");
    var DecompressedFile = filename.Substring(0,filename.Length-3);
    byte[] working = new byte[WORKING_BUFFER_SIZE];
    int n= 1;
    using (System.IO.Stream input = System.IO.File.OpenRead(filename))
    {
        using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
        {
            using (var output = System.IO.File.Create(DecompressedFile))
            {
                while (n !=0)
                {
                    n= decompressor.Read(working, 0, working.Length);
                    if (n > 0)
                    {
                        output.Write(working, 0, n);
                    }
                }
            }
        }
    }
}
Private Sub GunZipFile(ByVal filename as String)
    If Not (filename.EndsWith(".gz)) Then
        Throw New ArgumentException("filename")
    End If
    Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
    Dim working(WORKING_BUFFER_SIZE) as Byte
    Dim n As Integer = 1
    Using input As Stream = File.OpenRead(filename)
        Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
            Using output As Stream = File.Create(UncompressedFile)
                Do
                    n= decompressor.Read(working, 0, working.Length)
                    If n > 0 Then
                        output.Write(working, 0, n)
                    End IF
                Loop While (n  > 0)
            End Using
        End Using
    End Using
End Sub

GZipStream(Stream, CompressionMode, CompressionLevel)

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

Declaration
public GZipStream(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 GZipStream will compress or decompress.

CompressionLevel level

A tuning knob to trade speed for effectiveness.

Remarks

The CompressionMode (Compress or Decompress) also establishes the "direction" of the stream. A GZipStream with CompressionMode.Compress works only through Write(). A GZipStream with CompressionMode.Decompress works only through Read().

Examples

This example shows how to use a GZipStream to compress a file into a .gz file.

using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
    using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
    {
        using (Stream compressor = new GZipStream(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 & ".gz")
        Using compressor As Stream = New GZipStream(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

GZipStream(Stream, CompressionMode, CompressionLevel, Boolean)

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

Declaration
public GZipStream(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 GZipStream 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

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 compressed data has been written to it. Specify true for the leaveOpen parameter to leave the stream open.

As noted in the class documentation, the CompressionMode (Compress or Decompress) also establishes the "direction" of the stream. A GZipStream with CompressionMode.Compress works only through Write(). A GZipStream with CompressionMode.Decompress works only through Read().

Examples

This example shows how to use a GZipStream to compress data.

using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
    using (var raw = System.IO.File.Create(outputFile))
    {
        using (Stream compressor = new GZipStream(raw, 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);
            }
        }
    }
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
    Using raw As FileStream = File.Create(outputFile)
    Using compressor As Stream = New GZipStream(raw, 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
End Using

GZipStream(Stream, CompressionMode, Boolean)

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

Declaration
public GZipStream(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 GZipStream will compress or decompress.

System.Boolean leaveOpen

true if the application would like the base 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 compressed data has been written to it. Specify true for the leaveOpen parameter to leave the stream open.

The CompressionMode (Compress or Decompress) also establishes the "direction" of the stream. A GZipStream with CompressionMode.Compress works only through Write(). A GZipStream with CompressionMode.Decompress works only through Read().

The GZipStream will use the default compression level. If you want to specify the compression level, see GZipStream(Stream, CompressionMode, CompressionLevel, Boolean).

See the other overloads of this constructor for example code.

Fields

LastModified

The last modified time for the GZIP stream.

Declaration
public DateTime? LastModified
Field Value
Type Description
System.Nullable<System.DateTime>
Remarks

GZIP allows the storage of a last modified time with each GZIP entry. When compressing data, you can set this before the first call to Write(). When decompressing, you can retrieve this value any time after the first call to Read().

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.

Comment

The comment on the GZIP stream.

Declaration
public string Comment { get; set; }
Property Value
Type Description
System.String
Remarks

The GZIP format allows for each file to optionally have an associated comment stored with the file. The comment is encoded with the ISO-8859-1 code page. To include a comment in a GZIP stream you create, set this property before calling Write() for the first time on the GZipStream.

When using GZipStream to decompress, you can retrieve this property after the first call to Read(). If no comment has been set in the GZIP bytestream, the Comment property will return null (Nothing in VB).

Crc32

The CRC on the GZIP stream.

Declaration
public int Crc32 { get; }
Property Value
Type Description
System.Int32
Remarks

This is used for internal error checking. You probably don't need to look at this property.

FileName

The FileName for the GZIP stream.

Declaration
public string FileName { get; set; }
Property Value
Type Description
System.String
Remarks

The GZIP format optionally allows each file to have an associated filename. When compressing data (through Write()), set this FileName before calling Write() the first time on the GZipStream. The actual filename is encoded into the GZIP bytestream with the ISO-8859-1 code page, according to RFC 1952. It is the application's responsibility to insure that the FileName can be encoded and decoded correctly with this code page.

When decompressing (through Read()), you can retrieve this value any time after the first Read(). In the case where there was no filename encoded into the GZIP bytestream, the property will return null (Nothing in VB).

FlushMode

This property sets the flush behavior on the stream.

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

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.

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 GZip.

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[])

CompressString(String)

Compress a string into a byte array using GZip.

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[])

Dispose(Boolean)

Dispose the stream.

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

indicates whether 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.

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 and decompress data from the source stream.

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

The buffer into which the decompressed 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

With a GZipStream, decompression is done through reading.

Examples
byte[] working = new byte[WORKING_BUFFER_SIZE];
using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
{
    using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
    {
        using (var output = System.IO.File.Create(_DecompressedFile))
        {
            int n;
            while ((n= decompressor.Read(working, 0, working.Length)) !=0)
            {
                output.Write(working, 0, n);
            }
        }
    }
}

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

irrelevant; it will always throw!

System.IO.SeekOrigin origin

irrelevant; 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

irrelevant; this method will always throw!

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

UncompressBuffer(Byte[])

Uncompress a GZip'ed 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 GZip.

Returns
Type Description
System.Byte[]

The data in uncompressed form

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

UncompressString(Byte[])

Uncompress a GZip'ed byte array into a single string.

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

A buffer containing GZIP-compressed data.

Returns
Type Description
System.String

The uncompressed string

See Also
CompressString(String)
UncompressBuffer(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 GZipStream to compress data while writing, you can create a GZipStream with CompressionMode.Compress, and a writable output stream. Then call Write() on that GZipStream, providing uncompressed data as input. The data sent to the output stream will be the compressed form of the data written.

A GZipStream can be used for Read() or Write(), but not both. Writing implies compression. Reading implies decompression.

Implements

System.IAsyncDisposable
System.IDisposable

See Also

DeflateStream
ZlibStream
In This Article
Back to top Generated by DocFX