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 の部分読み取りと 0 バイト読み取り」を参照してください。

プロパティを使用して、 CanRead 現在のインスタンスが読み取りをサポートしているかどうかを判断します。 メソッドを ReadAsync 使用して、現在のストリームから非同期的に読み取ります。

このメソッドは、現在の buffer.Length ストリームから最大バイト数を読み取り、 に buffer格納します。 GZip ストリーム内の現在の位置は、読み取られたバイト数だけ進みます。ただし、例外が発生した場合、GZip ストリーム内の現在の位置は変更されません。 データが使用できない場合、このメソッドは少なくとも 1 バイトのデータを読み取ることができるまでブロックします。 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

読み取られる、圧縮解除されたバイトの最大数。

戻り値

圧縮解除されバイト配列に読み取られたバイト数。 既にストリームの末尾に到達している場合は、ゼロまたは読み取られたバイト数が返されます。

例外

array または buffernull です。

オブジェクトが作成されたとき、CompressionMode 値が Compress でした。

- または -

基になるストリームが読み取りをサポートしていません。

offset または count が 0 未満です。

または

array または buffer 長さからインデックスの開始点が より 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 の部分読み取りと 0 バイト読み取り」を参照してください。

データが無効な形式で見つかった場合は、 InvalidDataException がスローされます。 このメソッドの最後の操作の 1 つとして、巡回冗長チェック (CRC) が実行されます。

適用対象