GZipStream.Read Metodo

Definizione

Overload

Read(Span<Byte>)

Legge una sequenza di byte dal flusso GZip corrente in un intervallo di byte e fa avanzare la posizione all'interno del flusso GZip in base al numero di byte letti.

Read(Byte[], Int32, Int32)

Legge un numero di byte decompressi nella matrice di byte specificata.

Read(Span<Byte>)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Legge una sequenza di byte dal flusso GZip corrente in un intervallo di byte e fa avanzare la posizione all'interno del flusso GZip in base al numero di byte letti.

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

Parametri

buffer
Span<Byte>

Un'area di memoria. Quando questo metodo termina, il contenuto di quest'area viene sostituito dai byte letti dall'origine corrente.

Restituisce

Numero complessivo di byte letti nel buffer. È possibile che questo numero sia inferiore a quello dei byte allocati nel buffer se la quantità di byte disponibili è minore oppure che corrisponda a zero (0) se è stata raggiunta la fine del flusso.

Commenti

Importante

A partire da .NET 6, questo metodo potrebbe non leggere quanti byte sono stati richiesti. Per altre informazioni, vedere Letture parziali e zero byte in DeflateStream, GZipStream e CryptoStream.

Utilizzare la proprietà per determinare se l'istanza CanRead corrente supporta la lettura. Usare il ReadAsync metodo per leggere in modo asincrono dal flusso corrente.

Questo metodo legge un massimo di buffer.Length byte dal flusso corrente e li archivia in buffer. La posizione corrente all'interno del flusso GZip è avanzata dal numero di byte letti; Tuttavia, se si verifica un'eccezione, la posizione corrente all'interno del flusso GZip rimane invariata. Nel caso in cui non siano disponibili dati, questo metodo blocca fino a quando non è possibile leggere almeno un byte di dati. Read restituisce 0 solo quando non sono presenti più dati nel flusso e non è più previsto (ad esempio un socket chiuso o una fine di file). Il metodo è libero di restituire meno byte rispetto alla richiesta anche se la fine del flusso non è stata raggiunta.

Usare BinaryReader per la lettura dei tipi di dati primitivi.

Si applica a

Read(Byte[], Int32, Int32)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Legge un numero di byte decompressi nella matrice di byte specificata.

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

Parametri

arraybuffer
Byte[]

Matrice usata per archiviare i byte decompressi.

offset
Int32

Offset di byte in corrispondenza del quale verranno inseriti i byte di lettura.

count
Int32

Numero massimo di byte decompressi da leggere.

Restituisce

Numero di byte decompressi nella matrice di byte. Se è stata raggiunta la fine del flusso, viene restituito zero o il numero di byte letto.

Eccezioni

array o buffer è null.

Al momento della creazione dell'oggetto, il valore di CompressionMode era Compress.

-oppure-

Il flusso sottostante non supporta la lettura.

offset o count è minore di zero.

-oppure-

array o buffer lunghezza meno il punto iniziale dell'indice è minore di count.

Il formato dei dati non è valido.

Il flusso è chiuso.

Esempio

Nell'esempio seguente viene illustrato come comprimere e decomprimere i byte usando i Read metodi e 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

Commenti

Importante

A partire da .NET 6, questo metodo potrebbe non leggere quanti byte sono stati richiesti. Per altre informazioni, vedere Letture parziali e zero byte in DeflateStream, GZipStream e CryptoStream.

Se i dati vengono trovati in un formato non valido, viene generato un InvalidDataException oggetto . Viene eseguito un controllo di ridondanza ciclico (CRC) come una delle ultime operazioni di questo metodo.

Si applica a