GZipStream GZipStream GZipStream GZipStream Class

定义

提供用于压缩和解压缩流的方法和属性。 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
继承

示例

下面的示例演示如何使用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

注解

此类表示使用行业标准算法的无损文件压缩和解压缩 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,和CanRead When you inherit from GZipStream, you must override the following members: CanSeek, CanWrite, and CanRead.

构造函数

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.

属性

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)

方法

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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 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 占用的非托管资源,还可以另外再释放托管资源。 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()

检索控制此实例的生存期策略的当前生存期服务对象。 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 的浅表副本。 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)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 Stream 使用的所有资源。 Releases all resources used by the Stream.

(Inherited from Stream)

适用于