SharpZipLib压缩字符串

问题描述 投票:1回答:5

我需要压缩一个字符串以减少Web服务响应的大小。我在SharpZipLib样本中看到了单元测试,但不是我需要的一个例子。

在以下代码中,ZipOutputStream的构造函数返回异常:“No open entry”

        byte[] buffer = Encoding.UTF8.GetBytes(SomeLargeString);
        Debug.WriteLine(string.Format("Original byes of string: {0}", buffer.Length));

        MemoryStream ms = new MemoryStream();
        using (ZipOutputStream zipStream = new ZipOutputStream(ms))
        {
            zipStream.Write(buffer, 0, buffer.Length);
            Debug.WriteLine(string.Format("Compressed byes: {0}", ms.Length));
        }

        ms.Position = 0;
        MemoryStream outStream = new MemoryStream();

        byte[] compressed = new byte[ms.Length];
        ms.Read(compressed, 0, compressed.Length);

        byte[] gzBuffer = new byte[compressed.Length + 4];
        System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
        System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
        string compressedString = Convert.ToBase64String (gzBuffer);

我在哪里偏离轨道?我这让它变得比它应该更复杂吗?

c# sharpziplib
5个回答
3
投票

将数据转换为Base 64后,您确定数据会小得多吗?这将显着膨胀二进制数据(zip)。你不能使用HTTP压缩在传输级别解决问题吗?

这是一篇完整的文章,展示了如何进行往返拉链/解压缩。

http://paultechguy.blogspot.com/2008/09/zip-xml-in-memory-for-web-service.html


4
投票

对于来自Silverlight的Web服务通信压缩数据,我使用以下代码段:

private byte[] zipText(string text)
{
    if (text == null)
        return null;

    using(Stream memOutput = new MemoryStream())
    {
        using (GZipOutputStream zipOut = new GZipOutputStream(memOutput))
        {
            using (StreamWriter writer = new StreamWriter(zipOut))
            {
                writer.Write(text);

                writer.Flush();
                zipOut.Finish();

                byte[] bytes = new byte[memOutput.Length];
                memOutput.Seek(0, SeekOrigin.Begin);
                memOutput.Read(bytes, 0, bytes.Length);

                return bytes;
            }
        }
    }
}

private string unzipText(byte[] bytes)
{
    if (bytes == null)
        return null;

    using(Stream memInput = new MemoryStream(bytes))
    using(GZipInputStream zipInput = new GZipInputStream(memInput))
    using(StreamReader reader = new StreamReader(zipInput))
    {
        string text = reader.ReadToEnd();

        return text;
    }
}
  1. 我使用GZip而不是Zip压缩
  2. 预计文本将从类似的环境中读/写,所以我没有做任何额外的编码/解码。

我的情况是压缩json数据。根据我的观察,在某些情况下,大约95Kb的文本数据被压缩到1.5Kb。因此,即使将数据序列化为基数64,无论如何都可以节省大量流量。

发表我的回答,可能是某人节省了一些时间。


2
投票

您的代码存在一些问题:

  1. 使用流时始终刷新数据。
  2. 要从MemoryStream中读取数据,只需使用: byte [] data = ms.ToArray();
  3. Zip文件是可能包含多个条目(文件),注释的容器......您可能需要在开始向其写入数据之前调用PutNextEntry()以添加新条目。
  4. 如果您只需要压缩单个数据流(这是您的情况),您最好的选择就是使用deflate(或gzip)压缩来压缩单个数据流(实际上zip格式在内部使用gzip进行压缩它的条目......)。.Net提供了2个非常方便的数据压缩类:GZipStream和DeflateStream。一个很好的样本可以找到here

1
投票

在写入数据之前,需要调用PutNextEntry来添加标头。

答案复制自:http://community.sharpdevelop.net/forums/p/5910/16947.aspx


0
投票

我发现最简单的答案是在解压缩/压缩数据时处理字节并使用设置大小缓冲区将数据复制到可以使用的Stream对象,但是您喜欢:

    /// <summary>
    /// Unzips (inflates) zipped data.
    /// </summary>
    /// <param name="zippedData">The zipped data.</param>
    /// <returns>The inflated data.</returns>
    public Byte[] GUnzip(Byte[] zippedData)
    {
        using (MemoryStream unzippedData = new MemoryStream())
        {
            using (GZipInputStream zippedDataStream = new GZipInputStream(new MemoryStream(zippedData)))
            {
                CopyStream(zippedDataStream, unzippedData);
            }

            return unzippedData.ToArray();
        }
    }

    /// <summary>
    /// zips data.
    /// </summary>
    /// <param name="unzippedData">The unzipped data.</param>
    /// <returns>The zipped data.</returns>
    public Byte[] GZip(Byte[] unzippedData)
    {
        using (MemoryStream zippedData = new MemoryStream())
        {
            using (GZipOutputStream unzippedDataStream = new GZipOutputStream(new MemoryStream(unzippedData)))
            {
                CopyStream(unzippedDataStream, zippedData);
            }

            return zippedData.ToArray();
        }
    }

    /// <summary>
    /// Accepts an inStream, writes it to a buffer and goes out the outStream
    /// </summary>
    /// <param name="inStream">The input Stream</param>
    /// <param name="outStream">The output Stream</param>
    private static void CopyStream(Stream inStream, Stream outStream)
    {
        int nRead = 0;
        // Using a 2k buffer
        Byte[] theBuffer = new Byte[2048];

        while ((nRead = inStream.Read(theBuffer, 0, theBuffer.Length)) > 0)
        {
            outStream.Write(theBuffer, 0, nRead);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.