简体   繁体   English

使用GZip往返进行1个或多个字节截断

[英]1 or more bytes truncation with GZip round trip

I dont get it. 我不懂。 I have used a similar/same approach for many years now, and never experienced this. 我已经使用了类似/相同的方法多年,从未体验过这一点。

For some reason, that I did not pick up until today, a GZip round trip results in 1 or more bytes being truncated or data being garbled. 出于某种原因,直到今天我都没有接收,GZip往返导致1个或更多字节被截断或数据乱码。

I wrote a simple test to verify that something else is not affecting it. 我写了一个简单的测试来验证其他东西不会影响它。

This always fails with a 'length mismatch'. 这总是因“长度不匹配”而失败。

Can someone conform to me that I am not crazy? 有人能跟我说我不疯了吗? :) :)

Thanks 谢谢

leppie leppie

TEST 测试

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;

class Program
{
  const int BUFFER_SIZE = 8192;

  static void Main(string[] args)
  {
    var filename = args[0];
    var filedata = File.ReadAllBytes(filename);
    var cmp = Compress(filedata);
    var dec = Decompress(cmp);

    Assert(filedata, dec);

    Console.ReadLine();
  }

  static void Assert(byte[] orig, byte[] data)
  {
    if (orig.Length != data.Length)
    {
      Debug.Fail("length mismatch");
    }
    for (int i = 0; i < orig.Length; i++)
    {
      Debug.Assert(orig[i] == data[i], "data mismatch");
    }
  }

  static byte[] Compress(byte[] data)
  {
    var input = new MemoryStream(data);
    var output = new MemoryStream();

    var s = new GZipStream(output, CompressionMode.Compress);
    byte[] buffer = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
      s.Write(buffer, 0, read);
    }

    return output.ToArray();
  }

  static byte[] Decompress(byte[] data)
  {
    var input = new MemoryStream(data);
    var s = new GZipStream(input, CompressionMode.Decompress);

    var output = new MemoryStream();
    byte[] buffer = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = s.Read(buffer, 0, buffer.Length)) > 0)
    {
      output.Write(buffer, 0, read);
    }

    return output.ToArray();
  }
}

I have tried it with closing the streams properly too, with different buffer sizes, all the same result. 我已经尝试过正确关闭流,具有不同的缓冲区大小,所有相同的结果。

OK, found the problem. 好的,发现了问题。

You need to close the compression stream before retrieving the bytes. 您需要在检索字节之前关闭压缩流。

Eg: 例如:

s.Close();
return output.ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM