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
繼承

範例

下列範例顯示如何使用 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 類別使用與 GZipStream 類別所使用的 gzip 資料格式相同的壓縮演算法。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 類別的新執行個體。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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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 所使用的 unmanaged 資源並選擇性地釋放 managed 的資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 的淺層複本 (Shallow Copy)。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.

適用於