共用方式為


GZipStream.Read 方法

定義

多載

Read(Span<Byte>)

將位元組序列從目前的 GZip 資料流程讀取到位元組範圍,並將 GZip 資料流內位置前移到讀取的位元組數目。

Read(Byte[], Int32, Int32)

將大量解壓縮的位元組讀入指定的位元組陣列。

Read(Span<Byte>)

來源:
GZipStream.cs
來源:
GZipStream.cs
來源:
GZipStream.cs

將位元組序列從目前的 GZip 資料流程讀取到位元組範圍,並將 GZip 資料流內位置前移到讀取的位元組數目。

public:
 override int Read(Span<System::Byte> buffer);
public override int Read (Span<byte> buffer);
override this.Read : Span<byte> -> int
Public Overrides Function Read (buffer As Span(Of Byte)) As Integer

參數

buffer
Span<Byte>

記憶體區域。 當這個方法傳回時,讀取自目前來源的位元組會取代此區域內容。

傳回

緩衝區所讀取的總位元組數。 如果目前無法取得足夠的位元組,則這個數目可能小於緩衝區所配置的位元組數,如果已經到達資料流末端,則為零 (0)。

備註

重要

從 .NET 6 開始,此方法可能不會讀取所要求的位元元組數目。 如需詳細資訊,請參閱 DeflateStream、GZipStream 和 CryptoStream 中的部分和零位元組讀取

CanRead使用屬性來判斷目前實例是否支援讀取。 ReadAsync使用方法,以異步方式從目前的數據流讀取。

這個方法會從目前的數據流讀取最多位元組, buffer.Length 並將其儲存在 buffer中。 GZip 數據流中的目前位置會依讀取的位元組數目進階;不過,如果發生例外狀況,GZip 數據流中的目前位置會保持不變。 如果沒有數據可用,這個方法會封鎖,直到可以讀取至少一個字節的數據為止。 Read 只有在數據流中沒有其他數據,而且沒有其他預期 (,例如封閉式套接字或檔案結尾) 時,才會傳回 0。 即使尚未達到數據流結尾,方法仍可傳回比要求較少的位元組。

用於 BinaryReader 讀取基本數據類型。

適用於

Read(Byte[], Int32, Int32)

來源:
GZipStream.cs
來源:
GZipStream.cs
來源:
GZipStream.cs

將大量解壓縮的位元組讀入指定的位元組陣列。

public:
 override int Read(cli::array <System::Byte> ^ array, int offset, int count);
public:
 override int Read(cli::array <System::Byte> ^ buffer, int offset, int count);
public override int Read (byte[] array, int offset, int count);
public override int Read (byte[] buffer, int offset, int count);
override this.Read : byte[] * int * int -> int
override this.Read : byte[] * int * int -> int
Public Overrides Function Read (array As Byte(), offset As Integer, count As Integer) As Integer
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

參數

arraybuffer
Byte[]

用於儲存解壓縮位元組的陣列。

offset
Int32

將放置讀取位元組的位元移。

count
Int32

要讀取的最大解壓縮位元組數。

傳回

解壓縮至位元組陣列的位元組數。 如果已達到資料流的結尾,則會傳回零或位元組數。

例外狀況

arraybuffernull

建立物件時,CompressionMode 的值為 Compress

-或-

基礎資料流不支援讀取。

offsetcount 小於零。

-或-

arraybuffer 長度減去索引起點小於 count

資料的格式無效。

資料流已關閉。

範例

下列範例示範如何使用 和 Write 方法來壓縮和解壓縮位元組Read

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public static class MemoryWriteReadExample
{
    private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    private static readonly byte[] s_messageBytes = Encoding.ASCII.GetBytes(Message);

    public static void Run()
    {
        Console.WriteLine($"The original string length is {s_messageBytes.Length} bytes.");
        using var stream = new MemoryStream();
        CompressBytesToStream(stream);
        Console.WriteLine($"The compressed stream length is {stream.Length} bytes.");
        int decompressedLength = DecompressStreamToBytes(stream);
        Console.WriteLine($"The decompressed string length is {decompressedLength} bytes, same as the original length.");
        /*
         Output:
            The original string length is 445 bytes.
            The compressed stream length is 282 bytes.
            The decompressed string length is 445 bytes, same as the original length.
        */
    }

    private static void CompressBytesToStream(Stream stream)
    {
        using var compressor = new GZipStream(stream, CompressionLevel.SmallestSize, leaveOpen: true);
        compressor.Write(s_messageBytes, 0, s_messageBytes.Length);
    }

    private static int DecompressStreamToBytes(Stream stream)
    {
        stream.Position = 0;
        int bufferSize = 512;
        byte[] buffer = new byte[bufferSize];
        using var gzipStream = new GZipStream(stream, CompressionMode.Decompress);

        int totalRead = 0;
        while (totalRead < buffer.Length)
        {
            int bytesRead = gzipStream.Read(buffer.AsSpan(totalRead));
            if (bytesRead == 0) break;
            totalRead += bytesRead;
        }

        return totalRead;
    }
}
open System.IO
open System.IO.Compression
open System.Text

let message =
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

let s_messageBytes = Encoding.ASCII.GetBytes message

let compressBytesToStream stream =
    use compressor =
        new GZipStream(stream, CompressionLevel.SmallestSize, leaveOpen = true)

    compressor.Write(s_messageBytes, 0, s_messageBytes.Length)

let decompressStreamToBytes (stream: Stream) =
    stream.Position <- 0
    let bufferSize = 512
    let decompressedBytes = Array.zeroCreate bufferSize
    use decompressor = new GZipStream(stream, CompressionMode.Decompress)
    decompressor.Read(decompressedBytes, 0, bufferSize)

[<EntryPoint>]
let main _ =
    printfn $"The original string length is {s_messageBytes.Length} bytes."
    use stream = new MemoryStream()
    compressBytesToStream stream
    printfn $"The compressed stream length is {stream.Length} bytes."
    let decompressedLength = decompressStreamToBytes stream
    printfn $"The decompressed string length is {decompressedLength} bytes, same as the original length."
    0

// Output:
//     The original string length is 445 bytes.
//     The compressed stream length is 282 bytes.
//     The decompressed string length is 445 bytes, same as the original length.
Imports System.IO
Imports System.IO.Compression
Imports System.Text

Module MemoryWriteReadExample
    Private Const Message As String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    Private ReadOnly s_messageBytes As Byte() = Encoding.ASCII.GetBytes(Message)

    Sub Main()
        Console.WriteLine($"The original string length is {s_messageBytes.Length} bytes.")

        Using stream = New MemoryStream()
            CompressBytesToStream(stream)
            Console.WriteLine($"The compressed stream length is {stream.Length} bytes.")
            Dim decompressedLength As Integer = DecompressStreamToBytes(stream)
            Console.WriteLine($"The decompressed string length is {decompressedLength} bytes, same as the original length.")
        End Using
        ' Output:
        '   The original string length is 445 bytes.
        '   The compressed stream length is 282 bytes.
        '   The decompressed string length is 445 bytes, same as the original length.
    End Sub

    Private Sub CompressBytesToStream(ByVal stream As Stream)
        Using compressor = New GZipStream(stream, CompressionLevel.SmallestSize, leaveOpen:=True)
            compressor.Write(s_messageBytes, 0, s_messageBytes.Length)
        End Using
    End Sub

    Private Function DecompressStreamToBytes(ByVal stream As Stream) As Integer
        stream.Position = 0
        Dim bufferSize As Integer = 512
        Dim decompressedBytes As Byte() = New Byte(bufferSize - 1) {}
        Using decompressor = New GZipStream(stream, CompressionMode.Decompress)
            Dim length As Integer = decompressor.Read(decompressedBytes, 0, bufferSize)
            Return length
        End Using
    End Function
End Module

備註

重要

從 .NET 6 開始,此方法可能不會讀取所要求的位元元組數目。 如需詳細資訊,請參閱 DeflateStream、GZipStream 和 CryptoStream 中的部分和零位元組讀取

如果找到格式無效的數據, InvalidDataException 則會擲回 。 迴圈備援檢查 (CRC) 會執行為此方法的最後一個作業之一。

適用於