다음을 통해 공유


GZipStream.Read 메서드

정의

오버로드

Name Description
Read(Span<Byte>)

현재 GZip 스트림에서 바이트 범위로 바이트 시퀀스를 읽고 읽은 바이트 수만큼 GZip 스트림 내의 위치를 이동합니다.

Read(Byte[], Int32, Int32)

압축 해제된 바이트를 지정된 바이트 배열로 읽습니다.

Read(Span<Byte>)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
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 스트림 내의 현재 위치는 변경되지 않습니다. 사용할 수 있는 데이터가 없는 경우 이 메서드는 하나 이상의 데이터를 읽을 수 있을 때까지 차단합니다. Read 는 스트림에 더 이상 데이터가 없고 더 이상 필요하지 않은 경우에만 0을 반환합니다(예: 닫힌 소켓 또는 파일 끝). 이 메서드는 스트림의 끝에 도달하지 않은 경우에도 요청된 것보다 적은 바이트를 반환할 수 있습니다.

기본 데이터 형식을 읽는 데 사용합니다 BinaryReader .

적용 대상

Read(Byte[], Int32, Int32)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
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

읽을 압축 해제된 최대 바이트 수입니다.

반환

바이트 배열로 압축 해제된 바이트 수입니다. 스트림의 끝에 도달하면 0 또는 읽은 바이트 수가 반환됩니다.

예외

array 또는 buffer .입니다 null.

개체 CompressionModeCompress 만들 때의 값입니다.

-또는-

기본 스트림은 읽기를 지원하지 않습니다.

offset 또는 count 0보다 작습니다.

-또는-

array 또는 buffer 길이에서 인덱스 시작점을 뺀 값이 .보다 count작습니다.

데이터가 잘못된 형식입니다.

스트림이 닫혔습니다.

예제

다음 예제에서는 및 메서드를 사용하여 바이트를 압축 및 압축 해제하는 ReadWrite 방법을 보여 줍니다.

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바이트 읽기를 참조하세요.

데이터가 잘못된 형식으로 발견되면 throw InvalidDataException 됩니다. CRC(순환 중복 검사)는 이 메서드의 마지막 작업 중 하나로 수행됩니다.

적용 대상