gpt4 book ai didi

C# MemoryStream & GZipInputStream : Can't . 读取超过256字节

转载 作者:行者123 更新时间:2023-11-30 22:52:15 33 4
gpt4 key购买 nike

我在使用 SharpZipLib 的 GZipInputStream 编写未压缩的 GZIP 流时遇到问题。我似乎只能获得 256 字节的数据,其余数据未写入并归零。已检查压缩流 (compressedSection),所有数据都在那里(1500+ 字节)。解压过程的片段如下:

int msiBuffer = 4096;
using (Stream msi = new MemoryStream(msiBuffer))
{
msi.Write(compressedSection, 0, compressedSection.Length);
msi.Position = 0;
int uncompressedIntSize = AllMethods.GetLittleEndianInt(uncompressedSize, 0); // Gets little endian value of uncompressed size into an integer

// SharpZipLib GZip method called
using (GZipInputStream decompressStream = new GZipInputStream(msi, uncompressedIntSize))
{
using (MemoryStream outputStream = new MemoryStream(uncompressedIntSize))
{
byte[] buffer = new byte[uncompressedIntSize];
decompressStream.Read(buffer, 0, uncompressedIntSize); // Stream is decompressed and read
outputStream.Write(buffer, 0, uncompressedIntSize);
using (var fs = new FileStream(kernelSectionUncompressed, FileMode.Create, FileAccess.Write))
{
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
outputStream.Close();
}
decompressStream.Close();

所以在这段代码中:

1)压缩段传入,准备解压。

2) 未压缩输出的预期大小(作为 2 字节小端值存储在文件头中)通过一种方法将其转换为整数。 header 较早被删除,因为它不是压缩的 GZIP 文件的一部分。

3) SharpLibZip 的 GZIP 流使用压缩文件流 (msi) 和等于 int uncompressedIntSize 的缓冲区声明(也使用静态值 4096 进行了测试)。

4) 我设置了一个 MemoryStream 来处理将输出写入文件,因为 GZipInputStream 没有读/写;它以预期的解压缩文件大小作为参数(容量)。

5) 流的读/写需要byte[]数组作为第一个参数,所以我设置了一个byte[]数组,它有足够的空间来获取解压输出的所有字节(本例中为3584字节,派生自 uncompressedIntSize)。

6) int GzipInputStream decompressStream 使用 .Read 并将缓冲区作为第一个参数,从偏移量 0 开始,使用 uncompressedIntSize 作为计数。检查此处的参数,缓冲区数组仍具有 3584 字节的容量,但只提供了 256 字节的数据。其余为零。

看起来 .Read 的输出被限制为 256 字节,但我不确定在哪里。 Streams 是否遗漏了什么,或者这是 .Read 的限制?

最佳答案

从流中读取时需要循环懒惰的方式可能是:

decompressStream.CopyTo(outputStream);

(但这不能保证在 uncompressedIntSize 字节后停止 - 它会尝试读取到 decompressStream 的末尾)

一个更手动的版本(遵守强加的长度限制)是:

const int BUFFER_SIZE = 1024; // whatever
var buffer = ArrayPool<byte>.Shared.Rent(BUFFER_SIZE);
try
{
int remaining = uncompressedIntSize, bytesRead;
while (remaining > 0 && // more to do, and making progress
(bytesRead = decompressStream.Read(
buffer, 0, Math.Min(remaining, buffer.Length))) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
remaining -= bytesRead;
}
if (remaining != 0) throw new EndOfStreamException();
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}

关于C# MemoryStream & GZipInputStream : Can't . 读取超过256字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58308066/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com