2 out of 4 rated this helpful - Rate this topic

DeflateStream Class

Provides methods and properties for compressing and decompressing streams using the Deflate algorithm.

System.Object
  System.MarshalByRefObject
    System.IO.Stream
      System.IO.Compression.DeflateStream

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

The DeflateStream type exposes the following members.

  Name Description
Public method Supported by the XNA Framework DeflateStream(Stream, CompressionMode) Initializes a new instance of the DeflateStream class using the specified stream and CompressionMode value.
Public method Supported by the XNA Framework DeflateStream(Stream, CompressionMode, Boolean) Initializes a new instance of the DeflateStream 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 DeflateStream 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 Ends 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 stream 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 operation is not supported and always throws a NotSupportedException. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public method Supported by the XNA Framework SetLength This operation 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 Deflate algorithm, an industry standard algorithm for lossless file compression and decompression. It uses a combination of the LZ77 algorithm and Huffman coding. Data can be produced or consumed, even for an arbitrarily long, sequentially presented input data stream, using only previously bound amount of intermediate storage. The format can be implemented readily in a manner not covered by patents. For more information, see RFC 1951. "DEFLATE Compressed Data Format Specification version 1.3."

This class does not inherently provide functionality for adding files to or extracting files from .zip archives.

The GZipStream class uses the gzip data format, which includes a cyclic redundancy check value for detecting data corruption. The gzip data format uses the same compression algorithm as the DeflateStream class.

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.

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


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

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 *.cmp files in the directory.
        foreach (FileInfo fi in di.GetFiles("*.cmp"))
        {
    		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 != ".cmp")
            {
                // Create the compressed file.
                using (FileStream outFile = 
                        File.Create(fi.FullName + ".cmp"))
                {
                    using (DeflateStream Compress = 
                        new DeflateStream(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.cmp.
        	string curFile = fi.FullName;
        	string origName = curFile.Remove(curFile.Length 
                    - fi.Extension.Length);

        	//Create the decompressed file.
        	using (FileStream outFile = File.Create(origName))
        	{
        	    using (DeflateStream Decompress = new DeflateStream(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.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Decompressing a compressed stream doesn't seem to work
$0Unless I missed something obvious, the following code should print "OK", but print 'FAILED" instead. (It's just comparing an initial string with the result of a compression/decompression cycle) $0 $0$0 $0        static void TestCompress() {$0 $0            string txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel dolor augue, quis volutpat turpis. Maecenas viverra hendrerit eleifend. Nulla tincidunt mattis risus, sit amet pellentesque velit pellentesque at. Maecenas ac arcu sit amet metus sagittis vehicula. Integer blandit lacus ac arcu eleifend eget hendrerit erat ultrices. Aliquam at ligula eros. Integer id enim a augue blandit vulputate. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc laoreet, erat ac ornare volutpat, sapien nibh hendrerit orci, id venenatis tellus elit in nisi. Proin nunc lectus, lacinia id imperdiet eu, rutrum sed velit. Vivamus semper tortor eu eros venenatis non scelerisque orci pretium. Nam tellus tellus, ornare lacinia placerat sit amet, venenatis vitae justo. Nunc massa eros, adipiscing in varius eu, consequat sit amet lacus. Phasellus sem mauris, so dales vel varius iaculis, dictum id elit. Nulla facilisi.";$0 $0$0 $0 $0            MemoryStream ms = new MemoryStream();$0 $0            byte[] compressed;$0 $0            using (System.IO.Compression.DeflateStream df = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress)) {$0 $0                byte[] bytes = Encoding.UTF8.GetBytes(txt);$0 $0                df.Write(bytes, 0, bytes.Length);$0 $0                df.Flush();$0 $0                compressed = ms.ToArray();$0 $0            }$0 $0$0 $0 $0            ms = new MemoryStream(compressed);$0 $0            string txt2;$0 $0            using (StreamReader sr = new StreamReader(new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress), Encoding.UTF8)) {$0 $0                txt2 = sr.ReadToEnd();$0 $0            }$0 $0            if (txt == txt2) Console.WriteLine("OK");$0 $0            else Console.WriteLine("FAILED");$0 $0        }$0 $0 $0$0 $0 $0$0 $0 $0---------------------------------------$0 Yes you missed something obvious :p $0String1 == String2 is almost always false.. $0 $0Instead try String1.Equals(String2). I guess it give OK then.$0
Creating and unpacking Zip files
A zip file is much more than a deflate stream, and has multiple files, encryption and so on. You can easily create, unpack and update Zip files using  SharpLibLib (#ziplib), a free open source library for .NET framework.

Both source code and DLL are available, with runtimes for Compact Framework as well. The main page at http://www.icsharpcode.net/OpenSource/SharpZipLib/ has links for download, the forum and the wiki. There is also a Silverlight port on CodePlex.

This code will create a zip file ...

FastZip fastZip = new FastZip();
bool recurse = true; // Include all files by recursing through the directory structure
string filter = null; // Dont filter any files at all
fastZip.CreateZip("fileName.zip", @"C:\SourceDirectory", recurse, filter);

and this will extract all the files from a zip ...

FastZip fastZip = new FastZip();
string fileFilter = null;
fastZip.ExtractZip(zipFileName, targetDir, fileFilter);
SharpZipLib is free and can be included in commercial closed-source applications.
DeflateStream does not handle ZIP files, but DotNetZip does.

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