【问题标题】:how to get position and length of unzipped gzipstream in c#?如何在 C# 中获取解压缩的 gzipstream 的位置和长度?
【发布时间】:2018-04-19 22:44:55
【问题描述】:

我正在尝试使用二进制阅读器读取 .gz 文件,首先使用 gzipstream 解压缩,然后使用 gzipstream 创建一个新的二进制阅读器。但是,当我尝试使用 BinaryReader 的 BaseStream.Position 和 BaseStream.Length 时(知道我何时处于文件末尾),我得到一个 NotSupportedException,检查 GZipStream 类中这些字段的文档显示:

长度
此属性不受支持,并且总是抛出 NotSupportedException。(覆盖 Stream.Length。)

位置
此属性不受支持,并且总是抛出 NotSupportedException。(覆盖 Stream.Position。)

所以我的问题是,当使用 BinaryReader 读取解压缩的 GZipStream 时,我如何知道我何时处于文件末尾?谢谢

这是我的代码:

Stream stream = new MemoryStream(textAsset.bytes);
GZipStream zippedStream = new GZipStream(stream, CompressionMode.Decompress);
using (BinaryReader reader = new BinaryReader(zippedStream))
    while(reader.BaseStream.Position != reader.BaseStream.Length)
    {
        //do stuff with BinaryReader
    }

以上抛出: NotSupportedException:不支持操作。 System.IO.Compression.DeflateStream.get_Position()

由于 while() 中的 BaseStream.Position 调用

【问题讨论】:

  • 我还没有真正使用过这个,但你不能一直读下去直到它失败吗?
  • BinaryReader 是一个 .Net 类。压缩文件不必遵循其规范。所以直接使用 zippedStream.Read 直到它返回
  • @Eser 检查

标签: c# gzip binaryreader


【解决方案1】:

您可以将zippedStream 复制到MemoryStream 实例,可以使用ToArray 函数完全读取。这是我能想到的最简单的解决方案。

Stream stream = new MemoryStream(textAsset.bytes);
byte[] result;
using (GZipStream zippedStream = new GZipStream(stream, CompressionMode.Decompress))
{
    using (MemoryStream reader = new MemoryStream())
    {
        zippedStream.CopyTo(reader);
        result = reader.ToArray();
    }
}

或者,如果您想分块读取流

using (GZipStream zippedStream = new GZipStream(stream, CompressionMode.Decompress))
{
    byte[] buffer = new byte[16 * 1024];
    int read;
    while ((read = zippedStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        // do work
    }
}

【讨论】:

  • GZipStream 不包含“CopyTo”的定义
  • @RussellButler 每个 stream 都包含一个 CopyTo for .Net>=4.0。 msdn.microsoft.com/en-us/library/… 和 msdn.microsoft.com/en-us/library/…
  • @RussellButler 您的编译器到底说了什么以及您在项目中使用的 .Net 版本是什么?
  • @YaroslavVeremenko 它只是说“GZipStream 不包含 CopyTo 的定义并且没有扩展方法 CopyTo”......不确定.Net 的版本,但我在 Unity 2017.1.1f1 中使用 c# ,所以也许是 4.6? blogs.unity3d.com/2017/07/11/introducing-unity-2017 无论如何我使用 >= 0 hack 解决了这个问题,所以没问题。不过感谢您的回复:)
  • @RussellButler 你的意思是你在我的回复中使用了第二段代码还是类似的?
【解决方案2】:

根据您要解码的内容,您可以使用 BinaryReader 将第一个类型读入字节数组,然后使用 BitConverter 将这些字节转换为您想要的类型。然后,您可以照常使用 BinaryReader,直到下一条记录开始。

byte[] headermarker = new byte[4];

int count;

// if bytes available in underlying stream.
while ((count = br.Read(headermarker, 0, 4) > 0 )
{
    Int32 marker = BitConverter.ToInt32(headermarker, 0);

    //
    // now use Binary Reader for the rest of the record until we loop
    //
 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多