ZLib减压

时间:2009-08-25 10:34:46

标签: c# zlib compression

我正在尝试使用zlib .net库压缩数据。无论未压缩字符串的内容如何,​​我似乎只在raw []中获得了两个字节的数据。

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    Stream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
    byte[] buffer = new byte[2000];
    int len;
    while ((len = input.Read(buffer, 0, 2000)) > 0)
    {
       output.Write(buffer, 0, len);
    }
    output.Flush();
}

1 个答案:

答案 0 :(得分:3)

这里的问题是ZOutputStream实际上在finish()方法(由Close调用)中将一些信息写入流中。 Close方法也会关闭基本流,因此在这种情况下使用不多。

将代码更改为以下代码应该有效:

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    ZOutputStream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    outZStream.finish();

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
    byte[] buffer = new byte[2000];
    int len;
    while ((len = input.Read(buffer, 0, 2000)) > 0)
    {
       output.Write(buffer, 0, len);
    }
    output.Flush();
}