使用ICSharpCode.SharpZLib压缩/解压给定的数据

先介绍一下ICSharpCode.SharpZLib的几个代码入口

  1. ZipOutputStream,提供数据压缩功能代码入口;
  2. ZipInputStream,提供数据解压功能代码入口;
  3. ZipEntry,压缩和解药的数据单元描述。

下面是简单的代码:

/*压缩数据*/

public static byte[] Compress(byte[] content)
{
    using (var memory = new MemoryStream())
    {
        var entry = new ZipEntry("email") { DateTime = DateTime.Now };
        var output = new ZipOutputStream(memory);
        output.SetLevel(9);
        output.PutNextEntry(entry);
        output.Write(content, 0, content.Length);
        output.Flush();
        output.Close();

        return memory.ToArray();
    }
}

/*解压数据*/

public static Dictionary<string, byte[]> Decompress(byte[] content)
{
    var dictionary = new Dictionary<string, byte[]>();
    var input = new MemoryStream(content);
    var zip = new ZipInputStream(input);
    try
    {
        ZipEntry entry;
        while ((entry = zip.GetNextEntry()) != null)
        {
            using (var output = new MemoryStream())
            {
                var buffer = new byte[2048];
                while (true)
                {
                    var size = zip.Read(buffer, 0, buffer.Length);
                    if (size == 0)
                    {
                        output.Flush();
                        dictionary[entry.Name] = output.ToArray();
                    }

                    output.Write(buffer, 0, size);
                }
            }
        }

        return dictionary;
    }
    finally
    {
        zip.Dispose();
        input.Dispose();
    }
}

你可能感兴趣的:(使用ICSharpCode.SharpZLib压缩/解压给定的数据)