GZipStream.Write 메서드

정의

오버로드

Write(ReadOnlySpan<Byte>)

읽기 전용 바이트 범위에서 현재 GZip 스트림에 바이트 시퀀스를 쓰고 쓴 바이트 수만큼 이 GZip 스트림에서 현재 위치를 앞으로 이동합니다.

Write(Byte[], Int32, Int32)

지정된 바이트 배열에서 압축된 바이트를 내부 GZip 스트림에 씁니다.

Write(ReadOnlySpan<Byte>)

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

읽기 전용 바이트 범위에서 현재 GZip 스트림에 바이트 시퀀스를 쓰고 쓴 바이트 수만큼 이 GZip 스트림에서 현재 위치를 앞으로 이동합니다.

public:
 override void Write(ReadOnlySpan<System::Byte> buffer);
public override void Write (ReadOnlySpan<byte> buffer);
override this.Write : ReadOnlySpan<byte> -> unit
Public Overrides Sub Write (buffer As ReadOnlySpan(Of Byte))

매개 변수

buffer
ReadOnlySpan<Byte>

메모리 영역입니다. 이 메서드는 이 영역의 내용을 현재의 GZip 스트림에 복사합니다.

설명

CanWrite 현재 instance 쓰기를 지원하는지 여부를 확인하려면 속성을 사용합니다. 메서드를 WriteAsync 사용하여 현재 스트림에 비동기적으로 씁니다.

쓰기 작업이 성공하면 GZip 스트림 내의 위치가 작성된 바이트 수만큼 진행됩니다. 예외가 발생하면 GZip 스트림 내의 위치는 변경되지 않은 상태로 유지됩니다.

적용 대상

Write(Byte[], Int32, Int32)

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

지정된 바이트 배열에서 압축된 바이트를 내부 GZip 스트림에 씁니다.

public:
 override void Write(cli::array <System::Byte> ^ array, int offset, int count);
public:
 override void Write(cli::array <System::Byte> ^ buffer, int offset, int count);
public override void Write (byte[] array, int offset, int count);
public override void Write (byte[] buffer, int offset, int count);
override this.Write : byte[] * int * int -> unit
override this.Write : byte[] * int * int -> unit
Public Overrides Sub Write (array As Byte(), offset As Integer, count As Integer)
Public Overrides Sub Write (buffer As Byte(), offset As Integer, count As Integer)

매개 변수

arraybuffer
Byte[]

압축할 데이터가 들어 있는 버퍼입니다.

offset
Int32

바이트를 읽을 바이트 오프셋입니다.

count
Int32

쓸 최대 바이트 수입니다.

예외

스트림이 닫혀 있어서 쓰기 작업을 수행할 수 없는 경우

예제

다음 예제에서는 및 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

설명

쓰기 작업은 즉시 발생하지 않을 수 있지만 버퍼 크기에 도달하거나 또는 Close 메서드가 호출될 때까지 Flush 버퍼링됩니다.

적용 대상