DeflateStream DeflateStream DeflateStream DeflateStream Class

Definition

提供了方法和屬性,以透過 Deflate 演算法來壓縮和解壓縮資料流。 Provides methods and properties for compressing and decompressing streams by using the Deflate algorithm.

public ref class DeflateStream : System::IO::Stream
public class DeflateStream : System.IO.Stream
type DeflateStream = class
    inherit Stream
Public Class DeflateStream
Inherits Stream
Inheritance

Examples

下列範例示範如何使用DeflateStream類別壓縮和解壓縮檔案的目錄。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
{
    static string directoryPath = @"c:\temp";
    public static void Main()
    {
        
        DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
           Compress(directorySelected);
    	

        foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.cmp"))
        {
            Decompress(fileToDecompress);
        }
    }

    public static void Compress(DirectoryInfo directorySelected)
    {
        
     
        foreach (FileInfo file in directorySelected.GetFiles("*.xml"))
        using (FileStream originalFileStream = file.OpenRead())
        {
            if ((File.GetAttributes(file.FullName) & FileAttributes.Hidden)
                != FileAttributes.Hidden & file.Extension != ".cmp")
            {
                using (FileStream compressedFileStream = File.Create(file.FullName + ".cmp"))
                {
                    using (DeflateStream compressionStream = new DeflateStream(compressedFileStream, CompressionMode.Compress))
                    {
                        originalFileStream.CopyTo(compressionStream);
                    }
                }

                FileInfo info = new FileInfo(directoryPath + "\\" + file.Name + ".cmp");
                Console.WriteLine("Compressed {0} from {1} to {2} bytes.", file.Name, file.Length, info.Length);
            }
        }
    }

    public static void Decompress(FileInfo fileToDecompress)
    {
        using (FileStream originalFileStream = fileToDecompress.OpenRead())
        {
            string currentFileName = fileToDecompress.FullName;
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

            using (FileStream decompressedFileStream = File.Create(newFileName))
        	{
                using (DeflateStream decompressionStream = new DeflateStream(originalFileStream, CompressionMode.Decompress))
        	    {
                    decompressionStream.CopyTo(decompressedFileStream);
                    Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
        	    }
        	}
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Public Class Program
    Shared directoryPath As String = "c:\temp"
    Public Shared Sub Main()

        Dim directorySelected As New DirectoryInfo(directoryPath)
        Compress(directorySelected)


        For Each fileToDecompress As FileInfo In directorySelected.GetFiles("*.cmp")
            Decompress(fileToDecompress)
        Next
    End Sub

    Public Shared Sub Compress(directorySelected As DirectoryInfo)

        For Each file__1 As FileInfo In directorySelected.GetFiles("*.xml")
            Using originalFileStream As FileStream = file__1.OpenRead()
                If (File.GetAttributes(file__1.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And file__1.Extension <> ".cmp" Then
                    Using compressedFileStream As FileStream = File.Create(file__1.FullName & ".cmp")
                        Using compressionStream As Compression.DeflateStream = New DeflateStream(compressedFileStream, CompressionMode.Compress)
                            originalFileStream.CopyTo(compressionStream)
                        End Using
                    End Using

                    Dim info As New FileInfo(directoryPath & "\" & file__1.Name & ".cmp")
                    Console.WriteLine("Compressed {0} from {1} to {2} bytes.", file__1.Name, file__1.Length, info.Length)
                End If
            End Using
        Next
    End Sub

    Public Shared Sub Decompress(fileToDecompress As FileInfo)
        Using originalFileStream As FileStream = fileToDecompress.OpenRead()
            Dim currentFileName As String = fileToDecompress.FullName
            Dim newFileName As String = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length)

            Using decompressedFileStream As FileStream = File.Create(newFileName)
                Using decompressionStream As New DeflateStream(originalFileStream, CompressionMode.Decompress)
                    decompressionStream.CopyTo(decompressedFileStream)
                    Console.WriteLine("Decompressed: {0}", fileToDecompress.Name)
                End Using
            End Using
        End Using
    End Sub
End Class

Remarks

此類別代表 Deflate 演算法,也就是不失真的檔案壓縮和解壓縮的業界標準演算法。This class represents the Deflate algorithm, which is an industry-standard algorithm for lossless file compression and decompression. 開頭.NET Framework 4.5.NET Framework 4.5,則DeflateStream類別會使用 zlib 程式庫。Starting with the .NET Framework 4.5.NET Framework 4.5, the DeflateStream class uses the zlib library. 如此一來,它提供更好的壓縮演算法,而且在大部分情況下,比起較小的壓縮的檔提供在舊版的.NET Framework。As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of the .NET Framework.

這個類別原本就提供將檔案加入至或從 zip 封存解壓縮檔案的功能。This class does not inherently provide functionality for adding files to or extracting files from zip archives. 若要使用的 zip 封存,請使用ZipArchiveZipArchiveEntry類別。To work with zip archives, use the ZipArchive and the ZipArchiveEntry classes.

DeflateStream類別會使用相同的壓縮演算法所使用的 gzip 資料格式為GZipStream類別。The DeflateStream class uses the same compression algorithm as the gzip data format used by the GZipStream class.

中的壓縮功能DeflateStreamGZipStream公開為資料流。The compression functionality in DeflateStream and GZipStream 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. DeflateStreamGZipStream類別最適合使用未壓縮的資料來源上。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.

Constructors

DeflateStream(Stream, CompressionLevel) DeflateStream(Stream, CompressionLevel) DeflateStream(Stream, CompressionLevel) DeflateStream(Stream, CompressionLevel)

使用指定的資料流和壓縮等級,初始化 DeflateStream 類別的新執行個體。 Initializes a new instance of the DeflateStream class by using the specified stream and compression level.

DeflateStream(Stream, CompressionLevel, Boolean) DeflateStream(Stream, CompressionLevel, Boolean) DeflateStream(Stream, CompressionLevel, Boolean) DeflateStream(Stream, CompressionLevel, Boolean)

使用指定的資料流和壓縮等級,初始化 DeflateStream 類別的新執行個體,並選擇性地保留資料流開啟狀態。 Initializes a new instance of the DeflateStream class by using the specified stream and compression level, and optionally leaves the stream open.

DeflateStream(Stream, CompressionMode) DeflateStream(Stream, CompressionMode) DeflateStream(Stream, CompressionMode) DeflateStream(Stream, CompressionMode)

使用指定的資料流和壓縮模式,初始化 DeflateStream 類別的新執行個體。 Initializes a new instance of the DeflateStream class by using the specified stream and compression mode.

DeflateStream(Stream, CompressionMode, Boolean) DeflateStream(Stream, CompressionMode, Boolean) DeflateStream(Stream, CompressionMode, Boolean) DeflateStream(Stream, CompressionMode, Boolean)

使用指定的資料流和壓縮模式,初始化 DeflateStream 類別的新執行個體,並選擇性地保留資料流開啟狀態。 Initializes a new instance of the DeflateStream class by using the specified stream and compression mode, and optionally leaves the stream open.

Properties

BaseStream BaseStream BaseStream BaseStream

取得基礎資料流的參考。 Gets a reference to the underlying stream.

CanRead CanRead CanRead CanRead

取得值,指出在解壓縮檔案時,資料流是否支援讀取。 Gets a value indicating whether the stream supports reading while decompressing a file.

CanSeek CanSeek CanSeek CanSeek

取得值,指出資料流是否支援搜尋。 Gets a value indicating whether the stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。 Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

取得值,指出資料流是否支援寫入。 Gets a value indicating whether the stream supports writing.

Length Length Length Length

這個屬性不受支援,而且永遠會擲回 NotSupportedException This property is not supported and always throws a NotSupportedException.

Position Position Position Position

這個屬性不受支援,而且永遠會擲回 NotSupportedException This property is not supported and always throws a NotSupportedException.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

取得或設定值 (以毫秒為單位),該值決定在逾時前資料流將嘗試讀取多長時間。 Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out.

(Inherited from Stream)
WriteTimeout WriteTimeout WriteTimeout WriteTimeout

取得或設定值 (以毫秒為單位),該值決定在逾時前資料流將嘗試寫入多長時間。 Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

Methods

BeginRead(Byte[], Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的讀取作業。 Begins an asynchronous read operation. (請考慮使用 ReadAsync(Byte[], Int32, Int32) 方法替代。) (Consider using the ReadAsync(Byte[], Int32, Int32) method instead.)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的讀取作業。 Begins an asynchronous read operation. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。) (Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。 Begins an asynchronous write operation. (請考慮使用 WriteAsync(Byte[], Int32, Int32) 方法替代。) (Consider using the WriteAsync(Byte[], Int32, Int32) method instead.)

Close() Close() Close() 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 from Stream)
CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。 Reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 Asynchronously reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) Inherited from Stream
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) 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.

(Inherited from Stream)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。 Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

配置 WaitHandle 物件。 Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

釋放 Stream 所使用的所有資源。 Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 DeflateStream 所使用的 Unmanaged 資源,並選擇性釋放 Managed 資源。 Releases the unmanaged resources used by the DeflateStream and optionally releases the managed resources.

EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

等候暫止的非同步讀取來完成。 Waits for the pending asynchronous read to complete. (請考慮使用 ReadAsync(Byte[], Int32, Int32) 方法替代。) (Consider using the ReadAsync(Byte[], Int32, Int32) method instead.)

EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

結束非同步的寫入作業。 Ends an asynchronous write operation. (請考慮使用 WriteAsync(Byte[], Int32, Int32) 方法替代。) (Consider using the WriteAsync(Byte[], Int32, Int32) method instead.)

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前物件。 Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

這個方法目前的實作沒有任何功能。 The current implementation of this method has no functionality.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。 Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) 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 from Stream)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。 Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。 Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

取得目前執行個體的 Type Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件來控制這個執行個體的存留期原則。 Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。 Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。 Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

提供 Contract 的支援。 Provides support for a Contract.

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

將大量解壓縮的位元組讀入指定的位元組陣列。 Reads a number of decompressed bytes into the specified byte array.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Inherited from Stream
ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) 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 from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)
ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) Inherited from Stream
ReadByte() ReadByte() ReadByte() ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。 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)
Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

這個作業不受支援,而且永遠會擲回 NotSupportedException This operation is not supported and always throws a NotSupportedException.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

這個作業不受支援,而且永遠會擲回 NotSupportedException This operation is not supported and always throws a NotSupportedException.

ToString() ToString() ToString() ToString()

傳回表示目前物件的字串。 Returns a string that represents the current object.

(Inherited from Object)
Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

從指定的位元組陣列將壓縮的位元組寫入基礎資料流。 Writes compressed bytes to the underlying stream from the specified byte array.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Inherited from Stream
WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) 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 from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) Inherited from Stream
WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。 Writes a byte to the current position in the stream and advances the position within the stream by one byte.

(Inherited from Stream)

Explicit Interface Implementations

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() Inherited from Stream

Applies to