GZipStream.Read Metoda

Definice

Přetížení

Read(Span<Byte>)

Přečte posloupnost bajtů z aktuálního datového proudu GZip do rozsahu bajtů a posune pozici v rámci datového proudu GZip o počet přečtených bajtů.

Read(Byte[], Int32, Int32)

Načte počet dekomprimovaných bajtů do zadaného pole bajtů.

Read(Span<Byte>)

Zdroj:
GZipStream.cs
Zdroj:
GZipStream.cs
Zdroj:
GZipStream.cs

Přečte posloupnost bajtů z aktuálního datového proudu GZip do rozsahu bajtů a posune pozici v rámci datového proudu GZip o počet přečtených bajtů.

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

Parametry

buffer
Span<Byte>

Oblast paměti. Při vrácení této metody se obsah této oblasti nahradí bajty načtenými z aktuálního zdroje.

Návraty

Celkový počet bajtů načtených do vyrovnávací paměti. To může být menší než počet bajtů přidělených ve vyrovnávací paměti, pokud tento počet bajtů není aktuálně k dispozici, nebo nula (0), pokud bylo dosaženo konce datového proudu.

Poznámky

Důležité

Počínaje verzí .NET 6 nemusí tato metoda číst tolik bajtů, kolik bylo požadováno. Další informace najdete v tématu Částečné a nulové bajtové čtení v deflateStream, GZipStream a CryptoStream.

CanRead Pomocí vlastnosti určete, jestli aktuální instance podporuje čtení. K asynchronnímu čtení z aktuálního datového ReadAsync proudu použijte metodu .

Tato metoda načte maximální počet bajtů z aktuálního buffer.Length datového proudu a uloží je do buffer. Aktuální pozice v rámci GZip streamu je rozšířena o počet přečtených bajtů; Pokud však dojde k výjimce, aktuální pozice v rámci datového proudu GZip zůstane beze změny. V případě, že nejsou k dispozici žádná data, tato metoda blokuje, dokud nebude možné číst alespoň jeden bajt dat. Read vrátí hodnotu 0 pouze v případě, že v datovém proudu nejsou žádná další data a neočekává se žádná další data (například uzavřený soket nebo konec souboru). Metoda může vrátit méně bajtů, než je požadováno, i když nebylo dosaženo konce datového proudu.

Slouží BinaryReader ke čtení primitivních datových typů.

Platí pro

Read(Byte[], Int32, Int32)

Zdroj:
GZipStream.cs
Zdroj:
GZipStream.cs
Zdroj:
GZipStream.cs

Načte počet dekomprimovaných bajtů do zadaného pole bajtů.

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

Parametry

arraybuffer
Byte[]

Pole sloužící k ukládání dekomprimovaných bajtů.

offset
Int32

Posun bajtů, na který se umístí přečtené bajty.

count
Int32

Maximální počet dekompresovaných bajtů ke čtení.

Návraty

Počet bajtů, které byly dekompresovány do pole bajtů. Pokud bylo dosaženo konce datového proudu, vrátí se nula nebo počet přečtených bajtů.

Výjimky

array nebo buffer je null.

Hodnota CompressionMode byla Compress při vytvoření objektu.

-nebo-

Podkladový datový proud nepodporuje čtení.

offset nebo count je menší než nula.

-nebo-

array nebo buffer délka minus počáteční bod indexu je menší než count.

Data jsou v neplatném formátu.

Datový proud se zavře.

Příklady

Následující příklad ukazuje, jak komprimovat a dekomprimovat bajty pomocí Read metod a Write .

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

Poznámky

Důležité

Počínaje verzí .NET 6 nemusí tato metoda číst tolik bajtů, kolik bylo požadováno. Další informace najdete v tématu Částečné a nulové bajtové čtení v deflateStream, GZipStream a CryptoStream.

Pokud se data najdou v neplatném formátu, vyvolá se InvalidDataException hodnota . Kontrola cyklické redundance (CRC) se provádí jako jedna z posledních operací této metody.

Platí pro