2 out of 6 rated this helpful Rate this topic

GZipStream Class

Updated: January 2012

Provides methods and properties used to compress and decompress streams.

System.Object
  System.MarshalByRefObject
    System.IO.Stream
      System.IO.Compression.GZipStream

Namespace:  System.IO.Compression
Assembly:  System (in System.dll)
public class GZipStream : Stream

The GZipStream type exposes the following members.

  Name Description
Public method Supported by the XNA Framework GZipStream(Stream, CompressionMode) Initializes a new instance of the GZipStream class using the specified stream and CompressionMode value.
Public method Supported by the XNA Framework GZipStream(Stream, CompressionMode, Boolean) Initializes a new instance of the GZipStream class using the specified stream and CompressionMode value, and a value that specifies whether to leave the stream open.
Top
  Name Description
Public property Supported by the XNA Framework BaseStream Gets a reference to the underlying stream.
Public property Supported by the XNA Framework CanRead Gets a value indicating whether the stream supports reading while decompressing a file. (Overrides Stream.CanRead.)
Public property Supported by the XNA Framework CanSeek Gets a value indicating whether the stream supports seeking. (Overrides Stream.CanSeek.)
Public property Supported by the XNA Framework CanTimeout Gets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public property Supported by the XNA Framework CanWrite Gets a value indicating whether the stream supports writing. (Overrides Stream.CanWrite.)
Public property Supported by the XNA Framework Length This property is not supported and always throws a NotSupportedException. (Overrides Stream.Length.)
Public property Supported by the XNA Framework Position This property is not supported and always throws a NotSupportedException. (Overrides Stream.Position.)
Public property Supported by the XNA Framework ReadTimeout Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public property Supported by the XNA Framework WriteTimeout Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top
  Name Description
Public method Supported by the XNA Framework BeginRead Begins an asynchronous read operation. (Overrides Stream.BeginRead(Byte(), Int32, Int32, AsyncCallback, Object).)
Public method Supported by the XNA Framework BeginWrite Begins an asynchronous write operation. (Overrides Stream.BeginWrite(Byte(), Int32, Int32, AsyncCallback, Object).)
Public method Supported by the XNA Framework Close Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.)
Public method CopyTo(Stream) Reads the bytes from the current stream and writes them to the destination stream. (Inherited from Stream.)
Public method CopyTo(Stream, Int32) Reads all the bytes from the current stream and writes them to a destination stream, using a specified buffer size. (Inherited from Stream.)
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework CreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public method Supported by the XNA Framework Dispose Releases all resources used by the Stream. (Inherited from Stream.)
Protected method Supported by the XNA Framework Dispose(Boolean) Releases the unmanaged resources used by the GZipStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).)
Public method Supported by the XNA Framework EndRead Waits for the pending asynchronous read to complete. (Overrides Stream.EndRead(IAsyncResult).)
Public method Supported by the XNA Framework EndWrite Handles the end of an asynchronous write operation. (Overrides Stream.EndWrite(IAsyncResult).)
Public method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Flush Flushes the contents of the internal buffer of the current GZipStream object to the underlying stream. (Overrides Stream.Flush.)
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method ObjectInvariant Infrastructure. Provides support for a Contract. (Inherited from Stream.)
Public method Supported by the XNA Framework Read Reads a number of decompressed bytes into the specified byte array. (Overrides Stream.Read(Byte(), Int32, Int32).)
Public method Supported by the XNA Framework ReadByte Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. (Inherited from Stream.)
Public method Supported by the XNA Framework Seek This property is not supported and always throws a NotSupportedException. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public method Supported by the XNA Framework SetLength This property is not supported and always throws a NotSupportedException. (Overrides Stream.SetLength(Int64).)
Public method Supported by the XNA Framework ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Supported by the XNA Framework Write Writes compressed bytes to the underlying stream from the specified byte array. (Overrides Stream.Write(Byte(), Int32, Int32).)
Public method Supported by the XNA Framework WriteByte Writes a byte to the current position in the stream and advances the position within the stream by one byte. (Inherited from Stream.)
Top

This class represents the gzip data format, which uses an industry standard algorithm for lossless file compression and decompression. The format includes a cyclic redundancy check value for detecting data corruption. The gzip data format uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats. The format can be readily implemented in a manner not covered by patents.

Compressed GZipStream objects written to a file with an extension of .gz can be decompressed using many common compression tools; however, this class does not inherently provide functionality for adding files to or extracting files from .zip archives.

The GZipStream class cannot decompress data that results in over 8 GB of uncompressed data.

The compression functionality in DeflateStream and GZipStream is exposed as a stream. Data is read in on a byte-by-byte basis, so it is not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data. The DeflateStream and GZipStream classes are best used on uncompressed sources of data. If the source data is already compressed, using these classes may actually increase the size of the stream.

Notes to Inheritors

When you inherit from GZipStream, you must override the following members: CanSeek, CanWrite, and CanRead.

The following example shows how to use the GZipStream class to compress and decompress a directory of files.


using System;
using System.IO;
using System.IO.Compression;

namespace zip
{

    public class Program
    {

        public static void Main()
        {
            // Path to directory of files to compress and decompress.
            string dirpath = @"c:\users\public\reports";

            DirectoryInfo di = new DirectoryInfo(dirpath);

            // Compress the directory's files.
            foreach (FileInfo fi in di.GetFiles())
            {
                Compress(fi);

            }

            // Decompress all *.gz files in the directory.
            foreach (FileInfo fi in di.GetFiles("*.gz"))
            {
                Decompress(fi);

            }


        }

        public static void Compress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing hidden and 
                // already compressed files.
                if ((File.GetAttributes(fi.FullName) 
                	& FileAttributes.Hidden)
                	!= FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    // Create the compressed file.
                    using (FileStream outFile = 
                    			File.Create(fi.FullName + ".gz"))
                    {
                        using (GZipStream Compress = 
                        	new GZipStream(outFile, 
                        	CompressionMode.Compress))
                        {
                            // Copy the source file into 
                            // the compression stream.
                        inFile.CopyTo(Compress);

                            Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                                fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                        }
                    }
                }
            }
        }

        public static void Decompress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.
                string curFile = fi.FullName;
                string origName = curFile.Remove(curFile.Length - 
                		fi.Extension.Length);

                //Create the decompressed file.
                using (FileStream outFile = File.Create(origName))
                {
                    using (GZipStream Decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream 
                        // into the output file.
            		    Decompress.CopyTo(outFile);
            		    
                        Console.WriteLine("Decompressed: {0}", fi.Name);

                    }
                }
            }
        }

    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Date

History

Reason

January 2012

Added information about decompression size limit.

Content bug fix.

Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
You need to know what the zip contains
The example works well and unzips the file you specify.  If the gz file contains many files, this code won't work.  It assumes 1 file in the zip and uses the zip file name as the output name (without the extension).
If the input zip contains 2 Word documents and 3 Excel documents, this code won't do it.  Need to get a directory of the files contained within the zip file and unzip each one individually.
It works!
Great!

It works on .NET 2.0 & VS2005 after using Maira Wenzel's solution.

I modified the original code as below.
//inFile.CopyTo(Compress);
CopyStream(inFile, Compress);
//Decompress.CopyTo(outFile);
CopyStream(Decompress, outFile);

I compared the compress result.
It is not good as WinRAR. Assumed that my Source txt file size is: 2.150K.

with the GZipStream Class: the .gz file size is 106K.

otherwise with the Winrar: the .rar file size is 50K only.

Thanks.

Nano HE
Damaged files
The above example is flawed and will produce damaged files.  However, the fix is simple.  Close the FileStream objects and the GzipStream object when you get done with them.  If everything is closed properly, then you files won't be damaged.
Example doesn't work
I tried the example for compressing data right from this page and it doesn't work.
It is exactly the same code. The gz file has the same size as the input file. It is simply damaged.
I can open the resulting gz file in 7zip and the fiel I compresed is shown, but without extension and also damaged - not readable.

I for myself figured out, the GZipStream class simply doesn't work.
Compressing a 52bytes string results in 152bytes Data...
Reading Zero bytes as the first chunk
Hi everybody,
During decompression of a byte array, I noticed that the first uncompressed chunk of data (returned from Read(byte[]...) method) reads NOTHING! so I have to implement the decompress method as below (.NET 3.5)

        private static byte[] GetOutput(GZipStream stream)
        {
            MemoryStream output = new  MemoryStream();
            int read = ReadChunk(stream, output); // will not return anything!!!!!
            do
            {
                read = ReadChunk(stream, output);
            } while (read > 0);
            return output.ToArray();
        }
is it normal?

Bakhshi


EDITED: Here is the calling method:

        public static byte[] Decompress(byte[] compressed)
        {
            MemoryStream input = new MemoryStream(compressed);
            GZipStream stream = new GZipStream(input, CompressionMode.Decompress);
            return GetOutput(stream);
        }


FileStream.CopyTo not part of .NET 3.5
I filtered my search on .NET 3.5 and still I got this page, even though it is for .NET 4. In .NET 3.5 there is not FileStream.CopyTo function. This is in .NET 4.

However, if you have .NET 3.5 and not .NET 4, you can download a dll that you can add a reference to:
PGK.Extensions.dll
http://dnpextensions.codeplex.com/

---

You can still access previous versions of the documentation. Currently, the version selection is only available in Classic view mode (the old MSDN style). To switch from Lightweight view to Classic view, click Preferences on the top right corner and select Classic.

The direct link to the .NET 3.5 version of this topic is: http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(VS.90).aspx

Regards,

Maira Wenzel
CLR Documentation Manager
FileSream.CopyTo equivalent for .NET < 4.0

Since FileStream.CopyTo is a .NET 4.0 feature, the above code is it's replacement in the .NET 2.0, .NET 3.0, .NET 3.5

private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0) return;
output.Write (buffer, 0, read);
}
}

To use it, just copy the above function in your code together with the example provided from MSDN and then replace the input.CopyTo(output) lines with the above function, so it will look like this:

CopyStream(input, output);

NOTE: The real power of GZip is in the files of any kind expect .jpg pictures. The .jpg picture compression rate is very bad, because it actually raises the compressed file size and not lowers it. Or maybe it's just the .NET 2.0 version of GZip.

But for all other file types, the compressed size is reduced to almost 50% of the original uncompressed file.

---

This is the .NET 4 version of the documentation, so it's expected that the revisit samples to take advantage of new APIs available. To obtain the sample available for .NET 3.5, go to http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(VS.90).aspx.

Maira Wenzel
CLR Documentation Manager

GZipStream doesn't handle ZIP files, but DotNetZip does.

GZipStream doesn't handle ZIP files, but DotNetZip does. You can use DotNetZip (http://dotnetzip.codeplex.com ), a free 3rd-party library, to create and read zip files from within any .NET application.

This code in C#, zips all the files in a specified directory.

using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX");
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ;
zip.Save(zipFileToCreate);
}



This code in C#, unzips a zipfile:

      string unpackDirectory = "ExtractedFiles";
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
foreach (ZipEntry e in zip1)
{
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}


DotNetZip is free.