DeflateStream 类

定义

提供使用 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
继承

示例

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

注解

此类表示 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 存档或从 zip 存档中提取文件的功能。This class does not inherently provide functionality for adding files to or extracting files from zip archives. 若要使用 zip 存档,请使用ZipArchive ZipArchiveEntry和类。To work with zip archives, use the ZipArchive and the ZipArchiveEntry classes.

类使用与GZipStream类使用的 gzip 数据格式相同的压缩算法。 DeflateStreamThe 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.

构造函数

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 类的新实例,有选择性的打开流。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 类的新实例。Initializes a new instance of the DeflateStream class by using the specified stream and compression mode.

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.

属性

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)

使用指定的缓冲区大小,从当前 Deflate 流中读取字节并将其写入到另一流中。Reads the bytes from the current Deflate 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)

使用指定的缓冲区大小,从当前 Deflate 流中异步读取字节并将其写入到另一流中。Asynchronously reads the bytes from the current Deflate 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)

释放由 DeflateStream 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the DeflateStream and optionally releases the managed resources.

DisposeAsync()

异步释放 DeflateStream 使用的非托管资源。Asynchronously releases the unmanaged resources used by the DeflateStream.

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)

结束异步写操作。Ends 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)

异步清理此 Deflate 流的所有缓冲区,并使所有缓冲数据写入基础设备,并且监控取消请求。Asynchronously clears all buffers for this Deflate 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>)

将当前 Deflate 流中的一个字节序列读取到某字节范围,并按读取的字节数向前移动 Deflate 流中的位置。Reads a sequence of bytes from the current Deflate stream into a byte span and advances the position within the Deflate 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)

从当前 Deflate 流异步读取字节的序列,将其写入字节数组,按读取的字节数向前移动 Deflate 流中的位置,并监视取消请求。Asynchronously reads a sequence of bytes from the current Deflate stream, writes them to a byte array, advances the position within the Deflate stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

从当前 Deflate 流异步读取字节的序列,将其写入字节内存范围,按读取的字节数向前移动 Deflate 流中的位置,并监视取消请求。Asynchronously reads a sequence of bytes from the current Deflate stream, writes them to a byte memory range, advances the position within the Deflate stream by the number of bytes read, and monitors cancellation requests.

ReadByte()

从 Deflate 流中读取一个字节,并将流内的位置向前提升一个字节,或者如果已到达 Deflate 流结尾,则返回 -1。Reads a byte from the Deflate stream and advances the position within the stream by one byte, or returns -1 if at the end of the Deflate stream.

Seek(Int64, SeekOrigin)

此操作不受支持,它总是引发 NotSupportedExceptionThis operation is not supported and always throws a NotSupportedException.

SetLength(Int64)

此操作不受支持,它总是引发 NotSupportedExceptionThis operation is not supported and always throws a NotSupportedException.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
Write(Byte[], Int32, Int32)

从指定的字节数组中将压缩的字节写入基础流。Writes compressed bytes to the underlying stream from the specified byte array.

Write(ReadOnlySpan<Byte>)

将字节序列写入当前 Deflate 流,并按写入的字节数将 Deflate 流内的当前位置向前移动。Writes a sequence of bytes to the current Deflate stream and advances the current position within this Deflate 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)

从指定的字节数组中,将压缩的字节异步写入基础 Deflate 流。Asynchronously writes compressed bytes to the underlying Deflate stream from the specified byte array.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

从指定的只读内存区域中,将压缩的字节异步写入基础 Deflate 流。Asynchronously writes compressed bytes to the underlying Deflate stream from the specified read-only 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.

适用于