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继承时,必须重写以下成员: CanSeekCanWriteCanReadWhen 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)

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

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

返回一个表示当前对象的 string。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.

适用于