GZipStream.Read Metoda

Definicja

Przeciążenia

Read(Span<Byte>)

Odczytuje sekwencję bajtów z bieżącego strumienia GZip do zakresu bajtów i rozwija pozycję w strumieniu GZip przez liczbę odczytanych bajtów.

Read(Byte[], Int32, Int32)

Odczytuje liczbę dekompresowanych bajtów do określonej tablicy bajtów.

Read(Span<Byte>)

Źródło:
GZipStream.cs
Źródło:
GZipStream.cs
Źródło:
GZipStream.cs

Odczytuje sekwencję bajtów z bieżącego strumienia GZip do zakresu bajtów i rozwija pozycję w strumieniu GZip przez liczbę odczytanych bajtów.

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>

Region pamięci. Gdy ta metoda zwróci wartość , zawartość tego regionu jest zastępowana przez bajty odczytane z bieżącego źródła.

Zwraca

Całkowita liczba bajtów odczytanych do buforu. Może to być mniejsza niż liczba bajtów przydzielonych w buforze, jeśli liczba bajtów nie jest obecnie dostępna lub zero (0), jeśli koniec strumienia został osiągnięty.

Uwagi

Ważne

Począwszy od platformy .NET 6, ta metoda może nie odczytywać tyle bajtów, ile żądano. Aby uzyskać więcej informacji, zobacz Częściowe i zerowe odczyty odczytów w DeflateStream, GZipStream i CryptoStream.

Użyj właściwości , CanRead aby określić, czy bieżące wystąpienie obsługuje odczyt. ReadAsync Użyj metody , aby odczytywać asynchronicznie z bieżącego strumienia.

Ta metoda odczytuje maksymalnie buffer.Length bajty z bieżącego strumienia i przechowuje je w pliku buffer. Bieżące położenie w strumieniu GZip jest zaawansowane przez liczbę odczytanych bajtów; jednak w przypadku wystąpienia wyjątku bieżąca pozycja w strumieniu GZip pozostaje niezmieniona. W przypadku, gdy żadne dane nie są dostępne, ta metoda blokuje co najmniej jeden bajt danych. Read Metoda zwraca wartość 0 tylko wtedy, gdy nie ma więcej danych w strumieniu i nie oczekuje się więcej (np. zamkniętego gniazda lub końca pliku). Metoda jest bezpłatna, aby zwrócić mniej bajtów niż zażądano, nawet jeśli koniec strumienia nie został osiągnięty.

Służy BinaryReader do odczytywania typów danych pierwotnych.

Dotyczy

Read(Byte[], Int32, Int32)

Źródło:
GZipStream.cs
Źródło:
GZipStream.cs
Źródło:
GZipStream.cs

Odczytuje liczbę dekompresowanych bajtów do określonej tablicy bajtów.

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[]

Tablica używana do przechowywania dekompresowanych bajtów.

offset
Int32

Przesunięcie bajtu, w którym zostaną umieszczone bajty odczytu.

count
Int32

Maksymalna liczba dekompresowanych bajtów do odczytania.

Zwraca

Liczba bajtów, które zostały zdekompresowane do tablicy bajtów. Jeśli osiągnięto koniec strumienia, zwracana jest wartość zero lub liczba odczytanych bajtów.

Wyjątki

array lub buffer ma wartość null.

Wartość CompressionMode miała miejsce Compress podczas tworzenia obiektu.

-lub-

Podstawowy strumień nie obsługuje odczytu.

offset wartość lub count jest mniejsza niż zero.

-lub-

array lub buffer długość pomniejszona o punkt początkowy indeksu jest mniejsza niż count.

Dane są w nieprawidłowym formacie.

Strumień jest zamknięty.

Przykłady

W poniższym przykładzie pokazano, jak kompresować i dekompresować bajty przy użyciu Read metod i 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

Uwagi

Ważne

Począwszy od platformy .NET 6, ta metoda może nie odczytywać tyle bajtów, ile żądano. Aby uzyskać więcej informacji, zobacz Częściowe i zerowe odczyty odczytów w DeflateStream, GZipStream i CryptoStream.

Jeśli dane znajdują się w nieprawidłowym formacie, InvalidDataException zgłaszany jest element . Sprawdzanie nadmiarowości cyklicznej (CRC) jest wykonywane jako jedna z ostatnich operacji tej metody.

Dotyczy