Redigera

Dela via


GZipStream.Read Method

Definition

Overloads

Read(Span<Byte>)

Reads a sequence of bytes from the current GZip stream into a byte span and advances the position within the GZip stream by the number of bytes read.

Read(Byte[], Int32, Int32)

Reads a number of decompressed bytes into the specified byte array.

Read(Span<Byte>)

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

Reads a sequence of bytes from the current GZip stream into a byte span and advances the position within the GZip stream by the number of bytes read.

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

Parameters

buffer
Span<Byte>

A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current source.

Returns

The total number of bytes read into the buffer. This can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

Remarks

Important

Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream.

Use the CanRead property to determine whether the current instance supports reading. Use the ReadAsync method to read asynchronously from the current stream.

This method reads a maximum of buffer.Length bytes from the current stream and stores them in buffer. The current position within the GZip stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the GZip stream remains unchanged. In the event that no data is available, this method blocks until at least one byte of data can be read. Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the stream has not been reached.

Use BinaryReader for reading primitive data types.

Applies to

Read(Byte[], Int32, Int32)

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

Reads a number of decompressed bytes into the specified byte array.

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

Parameters

arraybuffer
Byte[]

The array used to store decompressed bytes.

offset
Int32

The byte offset at which the read bytes will be placed.

count
Int32

The maximum number of decompressed bytes to read.

Returns

The number of bytes that were decompressed into the byte array. If the end of the stream has been reached, zero or the number of bytes read is returned.

Exceptions

array or buffer is null.

The CompressionMode value was Compress when the object was created.

-or-

The underlying stream does not support reading.

offset or count is less than zero.

-or-

array or buffer length minus the index starting point is less than count.

The data is in an invalid format.

The stream is closed.

Examples

The following example shows how to compress and decompress bytes by using the Read and Write methods.

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

Remarks

Important

Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream.

If data is found in an invalid format, an InvalidDataException is thrown. A cyclic redundancy check (CRC) is performed as one of the last operations of this method.

Applies to