GZipStream Class
.NET Framework Class Library
GZipStream Class

Provides methods and properties used to compress and decompress streams.

Namespace:  System.IO.Compression
Assembly:  System (in System.dll)
Visual Basic
Public Class GZipStream _
    Inherits Stream
C#
public class GZipStream : Stream
Visual C++
public ref class GZipStream : public Stream
F#
type GZipStream =  
    class
        inherit Stream
    end

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

Visual Basic
Imports System.IO
Imports System.IO.Compression
Module Module1

    Sub Main()
        ' Path to directory of files to compress.
        Dim dirpath As String = "c:\users\public\reports"

        Dim di As DirectoryInfo = New DirectoryInfo(dirpath)


        ' Compress the directory's files.
        For Each fi As FileInfo In di.GetFiles()
            Compress(fi)
        Next

        ' Decompress all *.gz files in the directory.
        For Each fi As FileInfo In di.GetFiles("*.gz")
            Decompress(fi)
        Next

    End Sub

    ' Method to compress.
    Private Sub Compress(ByVal fi As FileInfo)
        ' Get the stream of the source file.
        Using inFile As FileStream = fi.OpenRead()
            ' Compressing:
            ' Prevent compressing hidden and already compressed files.

            If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) _
                <> FileAttributes.Hidden And fi.Extension <> ".gz" Then
                ' Create the compressed file.
                Using outFile As FileStream = File.Create(fi.FullName + ".gz")
                    Using Compress As GZipStream = _
                        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())

                    End Using
                End Using
            End If
        End Using
    End Sub

    ' Method to decompress.
    Private Sub Decompress(ByVal fi As FileInfo)
        ' Get the stream of the source file.
        Using inFile As FileStream = fi.OpenRead()
            ' Get orignial file extension, for example "doc" from report.doc.gz.
            Dim curFile As String = fi.FullName
            Dim origName = curFile.Remove(curFile.Length - fi.Extension.Length)

            ' Create the decompressed file.
            Using outFile As FileStream = File.Create(origName)
                Using Decompress As GZipStream = New GZipStream(inFile, _
                    CompressionMode.Decompress)
                    
                          ' Copy the decompression stream 
                        ' into the output file.
                        Decompress.CopyTo(outFile)

                    Console.WriteLine("Decompressed: {0}", fi.Name)

                End Using
            End Using
        End Using
    End Sub
End Module
C#
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);

                    }
                }
            }
        }

    }
}
System..::.Object
  System..::.MarshalByRefObject
    System.IO..::.Stream
      System.IO.Compression..::.GZipStream
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), 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.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
FileStream.CopyTo not part of .NET 3.5      Karwinlee ... Maira Wenzel -- MSFT   |   Edit   |   Show History
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
Tags What's this?: Add a tag
Flag as ContentBug
FileSream.CopyTo equivalent for .NET &lt; 4.0      Adorjan ... Maira Wenzel -- MSFT   |   Edit   |   Show History

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

Tags What's this?: Add a tag
Flag as ContentBug
GZipStream doesn't handle ZIP files, but DotNetZip does.      cheeso   |   Edit   |   Show History

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.

Tags What's this?: zip (x) Add a tag
Flag as ContentBug
Processing
Page view tracker