GZipStream.Read 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
多載
| 名稱 | Description |
|---|---|
| Read(Span<Byte>) |
從目前 GZip 串流讀取一串位元組到位元組區間,並依讀取位元組數推進 GZip 串流中的位置。 |
| Read(Byte[], Int32, Int32) |
將若干解壓縮的位元組讀取到指定的位元組陣列中。 |
Read(Span<Byte>)
從目前 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
參數
傳回
讀取到緩衝區的總位元組數。 如果目前沒有該位元組可用,這可能少於緩衝區中分配的位元組數;若已到達串流結束,則為零(0)。
備註
這很重要
從 .NET 6 開始,此方法可能無法讀取所需的位元組數量。 欲了解更多資訊,請參閱 DeflateStream、GZipStream 及 CryptoStream 中的部分與零位元組讀取。
利用該 CanRead 屬性判斷目前實例是否支援讀取。 使用該 ReadAsync 方法非同步讀取目前串流。
此方法從目前串流讀取最多位 buffer.Length 元組,並將其儲存在 buffer。 GZip 串流中的當前位置依讀取位元組數前進;但若發生例外,GZip 串流中的當前位置保持不變。 若無資料可用,此方法會阻塞,直到至少能讀取一個位元組資料。
Read 只有當串流中沒有更多資料且預期沒有更多資料(例如封閉套接字或檔案結束)時,才回傳 0。 即使串流尚未到達終點,此方法仍可自由回傳比請求的位元組少。
用於 BinaryReader 讀取原始資料型態。
適用於
Read(Byte[], Int32, Int32)
將若干解壓縮的位元組讀取到指定的位元組陣列中。
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 或 buffer 為 null。
資料格式無效。
溪流已經關閉。
範例
以下範例展示了如何使用 Read and Write 方法來壓縮和解壓位元組。
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 中的部分與零位元組讀取。
若發現資料格式無效,則拋出 a InvalidDataException 。 循環冗餘檢查(CRC)是此方法的最後操作之一。