This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Provides methods and properties for compressing and decompressing streams by using the Deflate algorithm.
public ref class DeflateStream : System::IO::Streampublic class DeflateStream : System.IO.Streamtype DeflateStream = class inherit StreamPublic Class DeflateStreamInherits StreamThe following example shows how to use theDeflateStream class to compress and decompress a file.
using System;using System.IO;using System.IO.Compression;public static class FileCompressionModeExample{ private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; private const string OriginalFileName = "original.txt"; private const string CompressedFileName = "compressed.dfl"; private const string DecompressedFileName = "decompressed.txt"; public static void Run() { CreateFileToCompress(); CompressFile(); DecompressFile(); PrintResults(); DeleteFiles(); /* Output: The original file 'original.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." The compressed file 'compressed.dfl' is 265 bytes. The decompressed file 'decompressed.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." */ } private static void CreateFileToCompress() => File.WriteAllText(OriginalFileName, Message); private static void CompressFile() { using FileStream originalFileStream = File.Open(OriginalFileName, FileMode.Open); using FileStream compressedFileStream = File.Create(CompressedFileName); using var compressor = new DeflateStream(compressedFileStream, CompressionMode.Compress); originalFileStream.CopyTo(compressor); } private static void DecompressFile() { using FileStream compressedFileStream = File.Open(CompressedFileName, FileMode.Open); using FileStream outputFileStream = File.Create(DecompressedFileName); using var decompressor = new DeflateStream(compressedFileStream, CompressionMode.Decompress); decompressor.CopyTo(outputFileStream); } private static void PrintResults() { long originalSize = new FileInfo(OriginalFileName).Length; long compressedSize = new FileInfo(CompressedFileName).Length; long decompressedSize = new FileInfo(DecompressedFileName).Length; Console.WriteLine($"The original file '{OriginalFileName}' is {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\""); Console.WriteLine($"The compressed file '{CompressedFileName}' is {compressedSize} bytes."); Console.WriteLine($"The decompressed file '{DecompressedFileName}' is {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\""); } private static void DeleteFiles() { File.Delete(OriginalFileName); File.Delete(CompressedFileName); File.Delete(DecompressedFileName); }}Imports System.IOImports System.IO.CompressionModule FileCompressionModeExample Private Const Message As String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." Private Const OriginalFileName As String = "original.txt" Private Const CompressedFileName As String = "compressed.dfl" Private Const DecompressedFileName As String = "decompressed.txt" Sub Main() CreateFileToCompress() CompressFile() DecompressFile() PrintResults() DeleteFiles() 'Output: ' The original file 'original.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ' The compressed file 'compressed.dfl' weighs 265 bytes. ' The decompressed file 'decompressed.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." End Sub Private Sub CreateFileToCompress() File.WriteAllText(OriginalFileName, Message) End Sub Private Sub CompressFile() Using originalFileStream As FileStream = File.Open(OriginalFileName, FileMode.Open) Using compressedFileStream As FileStream = File.Create(CompressedFileName) Using compressor = New DeflateStream(compressedFileStream, CompressionMode.Compress) originalFileStream.CopyTo(compressor) End Using End Using End Using End Sub Private Sub DecompressFile() Using compressedFileStream As FileStream = File.Open(CompressedFileName, FileMode.Open) Using outputFileStream As FileStream = File.Create(DecompressedFileName) Using decompressor = New DeflateStream(compressedFileStream, CompressionMode.Decompress) decompressor.CopyTo(outputFileStream) End Using End Using End Using End Sub Private Sub PrintResults() Dim originalSize As Long = New FileInfo(OriginalFileName).Length Dim compressedSize As Long = New FileInfo(CompressedFileName).Length Dim decompressedSize As Long = New FileInfo(DecompressedFileName).Length Console.WriteLine($"The original file '{OriginalFileName}' weighs {originalSize} bytes. Contents: ""{File.ReadAllText(OriginalFileName)}""") Console.WriteLine($"The compressed file '{CompressedFileName}' weighs {compressedSize} bytes.") Console.WriteLine($"The decompressed file '{DecompressedFileName}' weighs {decompressedSize} bytes. Contents: ""{File.ReadAllText(DecompressedFileName)}""") End Sub Private Sub DeleteFiles() File.Delete(OriginalFileName) File.Delete(CompressedFileName) File.Delete(DecompressedFileName) End SubEnd ModuleThis class represents the Deflate algorithm, which is an industry-standard algorithm for lossless file compression and decompression. Starting with .NET Framework 4.5, theDeflateStream class uses the zlib library. As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of .NET Framework.
This class does not inherently provide functionality for adding files to or extracting files from zip archives. To work with zip archives, use theZipArchive and theZipArchiveEntry classes.
TheDeflateStream class uses the same compression algorithm as the gzip data format used by theGZipStream class.
The compression functionality inDeflateStream andGZipStream is exposed as a stream. Data is read 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. TheDeflateStream andGZipStream 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 exact compressed byte sequence returned byDeflateStream can vary between .NET releases, platforms, and underlying compression engines. Changes in zlib versions, algorithm tweaks, and performance optimizations might produce different outputs for the same input data. But any data compressed byDeflateStream can always be decompressed to its original form without loss.
| Name | Description |
|---|---|
| DeflateStream(Stream, CompressionLevel, Boolean) | Initializes a new instance of theDeflateStream class by using the specified stream and compression level, and optionally leaves the stream open. |
| DeflateStream(Stream, CompressionLevel) | Initializes a new instance of theDeflateStream class by using the specified stream and compression level. |
| DeflateStream(Stream, CompressionMode, Boolean) | Initializes a new instance of theDeflateStream class by using the specified stream and compression mode, and optionally leaves the stream open. |
| DeflateStream(Stream, CompressionMode) | Initializes a new instance of theDeflateStream class by using the specified stream and compression mode. |
| DeflateStream(Stream, ZLibCompressionOptions, Boolean) | Initializes a new instance of theDeflateStream class by using the specified stream, compression options, and optionally leaves the stream open. |
| Name | Description |
|---|---|
| BaseStream | Gets a reference to the underlying stream. |
| CanRead | Gets a value indicating whether the stream supports reading while decompressing a file. |
| CanSeek | Gets a value indicating whether the stream supports seeking. |
| CanTimeout | Gets a value that determines whether the current stream can time out. (Inherited fromStream) |
| CanWrite | Gets a value indicating whether the stream supports writing. |
| Length | This property is not supported and always throws aNotSupportedException. |
| Position | This property is not supported and always throws aNotSupportedException. |
| ReadTimeout | Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. (Inherited fromStream) |
| WriteTimeout | Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. (Inherited fromStream) |
| Name | Description |
|---|---|
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) | Begins an asynchronous read operation. (Consider using theReadAsync(Byte[], Int32, Int32) method instead.) |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) | Begins an asynchronous write operation. (Consider using theWriteAsync(Byte[], Int32, Int32) method instead.) |
| Close() | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. (Inherited fromStream) |
| CopyTo(Stream, Int32) | Reads the bytes from the current Deflate stream and writes them to another stream, using a specified buffer size. |
| CopyTo(Stream, Int32) | Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CopyTo(Stream) | Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CopyToAsync(Stream, CancellationToken) | Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CopyToAsync(Stream, Int32, CancellationToken) | Asynchronously reads the bytes from the current Deflate stream and writes them to another stream, using a specified buffer size. |
| CopyToAsync(Stream, Int32, CancellationToken) | Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CopyToAsync(Stream, Int32) | Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CopyToAsync(Stream) | Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited fromStream) |
| CreateObjRef(Type) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited fromMarshalByRefObject) |
| CreateWaitHandle() | Obsolete. Obsolete. Obsolete. Allocates aWaitHandle object. (Inherited fromStream) |
| Dispose() | Releases all resources used by theStream. (Inherited fromStream) |
| Dispose(Boolean) | Releases the unmanaged resources used by theDeflateStream and optionally releases the managed resources. |
| DisposeAsync() | Asynchronously releases the unmanaged resources used by theDeflateStream. |
| EndRead(IAsyncResult) | Waits for the pending asynchronous read to complete. (Consider using theReadAsync(Byte[], Int32, Int32) method instead.) |
| EndWrite(IAsyncResult) | Ends an asynchronous write operation. (Consider using theWriteAsync(Byte[], Int32, Int32) method instead.) |
| Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited fromObject) |
| Flush() | The current implementation of this method has no functionality. |
| FlushAsync() | Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Inherited fromStream) |
| FlushAsync(CancellationToken) | Asynchronously clears all buffers for this Deflate stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. |
| FlushAsync(CancellationToken) | Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Inherited fromStream) |
| GetHashCode() | Serves as the default hash function. (Inherited fromObject) |
| GetLifetimeService() | Obsolete. Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited fromMarshalByRefObject) |
| GetType() | Gets theType of the current instance. (Inherited fromObject) |
| InitializeLifetimeService() | Obsolete. Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject) |
| MemberwiseClone() | Creates a shallow copy of the currentObject. (Inherited fromObject) |
| MemberwiseClone(Boolean) | Creates a shallow copy of the currentMarshalByRefObject object. (Inherited fromMarshalByRefObject) |
| ObjectInvariant() | Obsolete. Provides support for aContract. (Inherited fromStream) |
| Read(Byte[], Int32, Int32) | Reads a number of decompressed bytes into the specified byte array. |
| Read(Span<Byte>) | Reads a sequence of bytes from the current Deflate stream into a byte span and advances the position within the Deflate stream by the number of bytes read. |
| Read(Span<Byte>) | When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited fromStream) |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) | Asynchronously reads a sequence of bytes from the current Deflate stream, writes them to a byte array, advances the position within the Deflate stream by the number of bytes read, and monitors cancellation requests. |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) | Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Inherited fromStream) |
| ReadAsync(Byte[], Int32, Int32) | Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited fromStream) |
| ReadAsync(Memory<Byte>, CancellationToken) | Asynchronously reads a sequence of bytes from the current Deflate stream, writes them to a byte memory range, advances the position within the Deflate stream by the number of bytes read, and monitors cancellation requests. |
| ReadAsync(Memory<Byte>, CancellationToken) | Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Inherited fromStream) |
| ReadAtLeast(Span<Byte>, Int32, Boolean) | Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited fromStream) |
| ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken) | Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Inherited fromStream) |
| ReadByte() | Reads a byte from the Deflate stream and advances the position within the stream by one byte, or returns -1 if at the end of the Deflate stream. |
| 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 fromStream) |
| ReadExactly(Byte[], Int32, Int32) | Reads |
| ReadExactly(Span<Byte>) | Reads bytes from the current stream and advances the position within the stream until the |
| ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken) | Asynchronously reads |
| ReadExactlyAsync(Memory<Byte>, CancellationToken) | Asynchronously reads bytes from the current stream, advances the position within the stream until the |
| Seek(Int64, SeekOrigin) | This operation is not supported and always throws aNotSupportedException. |
| SetLength(Int64) | This operation is not supported and always throws aNotSupportedException. |
| ToString() | Returns a string that represents the current object. (Inherited fromObject) |
| Write(Byte[], Int32, Int32) | Writes compressed bytes to the underlying stream from the specified byte array. |
| Write(ReadOnlySpan<Byte>) | Writes a sequence of bytes to the current Deflate stream and advances the current position within this Deflate stream by the number of bytes written. |
| Write(ReadOnlySpan<Byte>) | When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited fromStream) |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) | Asynchronously writes compressed bytes to the underlying Deflate stream from the specified byte array. |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) | Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Inherited fromStream) |
| WriteAsync(Byte[], Int32, Int32) | Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited fromStream) |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) | Asynchronously writes compressed bytes to the underlying Deflate stream from the specified read-only memory region. |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) | Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Inherited fromStream) |
| WriteByte(Byte) | Writes a byte to the current Deflate stream and advances the current position within this Deflate stream by one. |
| WriteByte(Byte) | Writes a byte to the current position in the stream and advances the position within the stream by one byte. (Inherited fromStream) |
| Name | Description |
|---|---|
| CopyToAsync(Stream, PipeWriter, CancellationToken) | Asynchronously reads the bytes from theStream and writes them to the specifiedPipeWriter, using a cancellation token. |
| AsInputStream(Stream) | Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime. |
| AsOutputStream(Stream) | Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime. |
| AsRandomAccessStream(Stream) | Converts the specified stream to a random access stream. |
| ConfigureAwait(IAsyncDisposable, Boolean) | Configures how awaits on the tasks returned from an async disposable will be performed. |
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?