GZipStream 類別

定義

提供使用 GZip 資料格式規格來壓縮和解壓縮資料流的方法和屬性。Provides methods and properties used to compress and decompress streams by using the GZip data format specification.

public ref class GZipStream : System::IO::Stream
public class GZipStream : System.IO.Stream
type GZipStream = class
    inherit Stream
Public Class GZipStream
Inherits Stream
繼承

範例

下列範例顯示如何使用GZipStream類別來壓縮和解壓縮檔案目錄。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;

public class Program
{
    private static string directoryPath = @".\temp";
    public static void Main()
    {
        DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
        Compress(directorySelected);

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

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

                        }
                    }
                    FileInfo info = new FileInfo(directoryPath + Path.DirectorySeparatorChar + fileToCompress.Name + ".gz");
                    Console.WriteLine($"Compressed {fileToCompress.Name} from {fileToCompress.Length.ToString()} to {info.Length.ToString()} bytes.");
                }

            }
        }
    }

    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 (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    decompressionStream.CopyTo(decompressedFileStream);
                    Console.WriteLine($"Decompressed: {fileToDecompress.Name}");
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Private directoryPath As String = ".\temp"
    Public Sub Main()
        Dim directorySelected As New DirectoryInfo(directoryPath)
        Compress(directorySelected)

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

    Public Sub Compress(directorySelected As DirectoryInfo)
        For Each fileToCompress As FileInfo In directorySelected.GetFiles()
            Using originalFileStream As FileStream = fileToCompress.OpenRead()
                If (File.GetAttributes(fileToCompress.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And fileToCompress.Extension <> ".gz" Then
                    Using compressedFileStream As FileStream = File.Create(fileToCompress.FullName & ".gz")
                        Using compressionStream As New GZipStream(compressedFileStream, CompressionMode.Compress)

                            originalFileStream.CopyTo(compressionStream)
                        End Using
                    End Using
                    Dim info As New FileInfo(directoryPath & Path.DirectorySeparatorChar & fileToCompress.Name & ".gz")
                    Console.WriteLine($"Compressed {fileToCompress.Name} from {fileToCompress.Length.ToString()} to {info.Length.ToString()} bytes.")

                End If
            End Using
        Next
    End Sub


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

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

備註

此類別代表 gzip 資料格式,其使用業界標準的演算法來進行不失真的檔案壓縮和解壓縮。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. Gzip 資料格式使用與DeflateStream類別相同的演算法,但是可以擴充以使用其他壓縮格式。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.

.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 for compression. 因此,它提供更好的壓縮演算法,而且在大部分情況下,壓縮的檔案會比在舊版 .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.

寫入GZipStream副檔名為. gz 之檔案的壓縮物件可以使用許多常見的壓縮工具進行解壓縮; 不過,此類別原本就不會提供將檔案新增至 zip 封存或從中解壓縮檔案的功能。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.

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.

給繼承者的注意事項

當您繼承自GZipStream時,您必須覆寫下列成員CanSeekCanWrite、和CanReadWhen you inherit from GZipStream, you must override the following members: CanSeek, CanWrite, and CanRead.

建構函式

GZipStream(Stream, CompressionLevel)

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

GZipStream(Stream, CompressionLevel, Boolean)

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

GZipStream(Stream, CompressionMode)

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

GZipStream(Stream, CompressionMode, Boolean)

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

屬性

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.

(繼承來源 Stream)
CanWrite

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

Length

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

Position

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

ReadTimeout

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

(繼承來源 Stream)
WriteTimeout

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

(繼承來源 Stream)

方法

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

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

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()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。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.

(繼承來源 Stream)
CopyTo(Stream)

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

(繼承來源 Stream)
CopyTo(Stream, Int32)

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

CopyToAsync(Stream)

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

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

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

(繼承來源 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

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

CreateObjRef(Type)

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

(繼承來源 MarshalByRefObject)
CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

(繼承來源 Stream)
Dispose()

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

(繼承來源 Stream)
Dispose(Boolean)

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

DisposeAsync()

以非同步方式釋放 GZipStream 使用的不受控資源。Asynchronously releases the unmanaged resources used by the GZipStream.

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)

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

Equals(Object)

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

(繼承來源 Object)
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.

(繼承來源 Stream)
FlushAsync(CancellationToken)

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

GetHashCode()

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

(繼承來源 Object)
GetLifetimeService()

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

(繼承來源 MarshalByRefObject)
GetType()

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

(繼承來源 Object)
InitializeLifetimeService()

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

(繼承來源 MarshalByRefObject)
MemberwiseClone()

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

(繼承來源 Object)
MemberwiseClone(Boolean)

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

(繼承來源 MarshalByRefObject)
ObjectInvariant()

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

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

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

Read(Span<Byte>)

將位元組序列從目前的 GZip 資料流程讀取到位元組範圍,並將 GZip 資料流內位置前移到讀取的位元組數目。Reads a sequence of bytes from the current GZip stream into a byte span and advances the position within the GZip stream by the number of bytes read.

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.

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式將目前 GZip 資料流的位元組序列讀入位元組陣列中、依讀取的位元組數將 GZip 資料流中位置往前移,並監視取消要求。Asynchronously reads a sequence of bytes from the current GZip stream into a byte array, advances the position within the GZip stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

以非同步方式將目前 GZip 資料流的位元組序列讀入位元組記憶體區域中、依讀取的位元組數將 GZip 資料流中位置往前移,並監視取消要求。Asynchronously reads a sequence of bytes from the current GZip stream into a byte memory region, advances the position within the GZip stream by the number of bytes read, and monitors cancellation requests.

ReadByte()

從 GZip 資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在 GZip 資料流末端,則傳回 -1。Reads a byte from the GZip stream and advances the position within the stream by one byte, or returns -1 if at the end of the GZip stream.

Seek(Int64, SeekOrigin)

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

SetLength(Int64)

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

ToString()

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

(繼承來源 Object)
Write(Byte[], Int32, Int32)

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

Write(ReadOnlySpan<Byte>)

從唯讀位元組範圍將一系列位元組寫入目前的 GZip 資料流,並依寫入位元組數將這個 GZip 資料流中目前的位置往前移。Writes a sequence of bytes to the current GZip stream from a read-only byte span and advances the current position within this GZip stream by the number of bytes written.

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.

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式從指定位元組陣列將壓縮的位元組寫入基礎 GZip 資料流。Asynchronously writes compressed bytes to the underlying GZip stream from the specified byte array.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

從指定的唯讀位元組記憶體區域,以非同步方式將壓縮的位元組寫入基礎 GZip 資料流。Asynchronously writes compressed bytes to the underlying GZip stream from the specified read-only byte memory region.

WriteByte(Byte)

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

(繼承來源 Stream)

明確介面實作

IDisposable.Dispose()

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

(繼承來源 Stream)

擴充方法

AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸入資料流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸出資料流。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.

適用於