DeflateStream DeflateStream DeflateStream DeflateStream Class

定义

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

DeflateStream类使用 gzip 数据格式为使用相同的压缩算法GZipStream类。The 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(Stream, CompressionLevel) DeflateStream(Stream, CompressionLevel) 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(Stream, CompressionLevel, Boolean) DeflateStream(Stream, CompressionLevel, Boolean) 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(Stream, CompressionMode) DeflateStream(Stream, CompressionMode) 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(Stream, CompressionMode, Boolean) DeflateStream(Stream, CompressionMode, Boolean) 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 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

此属性不受支持,并且总是引发 NotSupportedExceptionThis property is not supported and always throws a NotSupportedException.

Position Position Position Position

此属性不受支持,并且总是引发 NotSupportedExceptionThis property is not supported and always throws a NotSupportedException.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取多长时间。Gets or sets a value, in milliseconds, 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 milliseconds, 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)
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)

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

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

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

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

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

获取当前实例的 TypeGets 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>)
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)
ReadByte() ReadByte() ReadByte() ReadByte()
Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

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

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

此操作不受支持,它总是引发 NotSupportedExceptionThis operation 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>)
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)
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)

扩展方法

AsInputStream(Stream) AsInputStream(Stream) AsInputStream(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) AsOutputStream(Stream) AsOutputStream(Stream) 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) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。Converts the specified stream to a random access stream.

适用于