GZipStream GZipStream GZipStream GZipStream Class

Definition

提供用於壓縮和解壓縮資料流的方法和屬性。 Provides methods and properties used to compress and decompress streams.

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

Examples

下列範例示範如何使用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;

namespace zip
{
    public class Program
    {
        private static string directoryPath = @"c:\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 + "\\" + fileToCompress.Name + ".gz");
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                        fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
                    }

                }
            }
        }

        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: {0}", fileToDecompress.Name);
                    }
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression
Module Module1

    Private directoryPath As String = "c:\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 & "\" & fileToCompress.Name & ".gz")
                    Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fileToCompress.Name,
                                      fileToCompress.Length.ToString(), info.Length.ToString())

                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: {0}", fileToDecompress.Name)
                End Using
            End Using
        End Using
    End Sub
End Module

Remarks

此類別代表會使用業界標準演算法的不失真的檔案壓縮和解壓縮 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.

Notes to Inheritors

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

Constructors

GZipStream(Stream, CompressionLevel) GZipStream(Stream, CompressionLevel) GZipStream(Stream, CompressionLevel) 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(Stream, CompressionLevel, Boolean) GZipStream(Stream, CompressionLevel, Boolean) 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(Stream, CompressionMode) GZipStream(Stream, CompressionMode) 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(Stream, CompressionMode, Boolean) GZipStream(Stream, CompressionMode, Boolean) 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.

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[], 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 the ReadAsync(Byte[], Int32, Int32) method instead.)

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)

釋放 GZipStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。 Releases the unmanaged resources used by the GZipStream 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)

處理非同步寫入作業的結束。 Handles the end of 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 property is not supported and always throws a NotSupportedException.

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

這個屬性不受支援,而且一律會擲回 NotSupportedException This property 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