DeflateStream.Read 方法

定义

重载

Read(Span<Byte>)

将当前 Deflate 流中的一个字节序列读取到某字节范围,并按读取的字节数向前移动 Deflate 流中的位置。

Read(Byte[], Int32, Int32)

将若干解压缩的字节读入指定的字节数组。

Read(Span<Byte>)

Source:
DeflateStream.cs
Source:
DeflateStream.cs
Source:
DeflateStream.cs

将当前 Deflate 流中的一个字节序列读取到某字节范围,并按读取的字节数向前移动 Deflate 流中的位置。

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 中的部分读取和零字节读取

CanRead使用 属性确定当前实例是否支持读取。 ReadAsync使用 方法从当前流异步读取。

此方法从当前流中读取最大字节并将其 buffer.Length 存储在 中 buffer。 Deflate 流中的当前位置按读取的字节数提前;但是,如果发生异常,Deflate 流中的当前位置保持不变。 如果没有任何数据可用,此方法将阻止,直到至少可以读取一个字节的数据。 Read 仅当流中没有更多数据并且预期不再 ((例如关闭的套接字或文件) 末尾)时,才返回 0。 即使尚未到达流的末尾,方法也可以自由返回比请求的更少的字节数。

用于 BinaryReader 读取基元数据类型。

适用于

Read(Byte[], Int32, Int32)

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

最多要读取的解压缩字节数。

返回

已读入到字节数组中的字节数。

例外

arraybuffernull

创建对象时 CompressionMode 值是 Compress

- 或 -

基础流不支持读取。

offsetcount 小于零。

arraybuffer 长度减去索引起始点小于 count

数据的格式无效。

流已关闭。

注解

重要

从 .NET 6 开始,此方法可能不会读取请求的字节数。 有关详细信息,请参阅 DeflateStream、GZipStream 和 CryptoStream 中的部分读取和零字节读取

以下示例演示如何使用 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 265 bytes.
            The decompressed string length is 445 bytes, same as the original length.
        */
    }

    private static void CompressBytesToStream(Stream stream)
    {
        using var compressor = new DeflateStream(stream, CompressionMode.Compress, 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 deflateStream = new DeflateStream(stream, CompressionMode.Decompress);

        int totalRead = 0;
        while (totalRead < buffer.Length)
        {
            int bytesRead = deflateStream.Read(buffer.AsSpan(totalRead));
            if (bytesRead == 0) break;
            totalRead += bytesRead;
        }

        return totalRead;
    }
}
module MemoryWriteReadExample

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 DeflateStream(stream, CompressionMode.Compress, 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 DeflateStream(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 265 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 265 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 DeflateStream(stream, CompressionMode.Compress, 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 DeflateStream(stream, CompressionMode.Decompress)
            Dim length As Integer = decompressor.Read(decompressedBytes, 0, bufferSize)
            Return length
        End Using
    End Function
End Module

适用于