`

.net 利用 GZipStream 压缩和解压缩

    博客分类:
  • .net
 
阅读更多

 

.net 利用 GZipStream 压缩和解压缩

1.GZipStream 类

 

此类在 .NET Framework 2.0 版中是新增的。

提供用于压缩和解压缩流的方法和属性

2.压缩byte[]

        /// <summary>
        /// 压缩数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress);
            zipStream.Write(data, 0, data.Length);//将数据压缩并写到基础流中
            zipStream.Close();
            return ms.ToArray();
        }

3.解压byte[]

        /// 解压数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public byte[] Decompress(byte[] data)
        {
            MemoryStream srcMs = new MemoryStream(data);
            GZipStream zipStream = new GZipStream(srcMs, CompressionMode.Decompress);
            MemoryStream ms = new MemoryStream();
            byte[] bytes = new byte[40960];
            int n;
            while ((n = zipStream.Read(bytes, 0, bytes.Length)) > 0)
            {
                ms.Write(bytes, 0, n);
            }
            zipStream.Close();
            return ms.ToArray();
        }

4.压缩byte[]数据,存放到文件中

/// <summary>
        /// 将指定的字节数组压缩,并写入到目标文件
        /// </summary>
        /// <param name="srcBuffer">指定的源字节数组</param>
        /// <param name="destFile">指定的目标文件</param>
        public static void CompressData(byte[] srcBuffer, string destFile)
        {
            FileStream destStream = null;
            GZipStream compressedStream = null;
            try
            {
                //打开文件流
                destStream = new FileStream(destFile, FileMode.OpenOrCreate, FileAccess.Write);
                //指定压缩的目的流(这里是文件流)
                compressedStream = new GZipStream(destStream, CompressionMode.Compress, true);
                //往目的流中写数据,而流将数据写到指定的文件
                compressedStream.Write(srcBuffer, 0, srcBuffer.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("压缩数据写入文件{0}时发生错误", destFile), ex);
            }
            finally
            {
                // Make sure we allways close all streams               
                if (null != compressedStream)
                {
                    compressedStream.Close();
                    compressedStream.Dispose();
                }

                if (null != destStream)
                    destStream.Close();
            }
        }
 

5.解压文件,得到byte[]数据

/// <summary>
        /// 将指定的文件解压,返回解压后的数据
        /// </summary>
        /// <param name="srcFile">指定的源文件</param>
        /// <returns>解压后得到的数据</returns>
        public static byte[] DecompressData(string srcFile)
        {
            if (false == File.Exists(srcFile))
                throw new FileNotFoundException(String.Format("找不到指定的文件{0}", srcFile));
            FileStream sourceStream = null;
            GZipStream decompressedStream = null;
            byte[] quartetBuffer = null;
            try
            {
                sourceStream = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true);

                // Read the footer to determine the length of the destiantion file
                //GZIP文件格式说明:
                //10字节的头,包含幻数、版本号以及时间戳 
                //可选的扩展头,如原文件名 
                //文件体,包括DEFLATE压缩的数据 
                //8字节的尾注,包括CRC-32校验和以及未压缩的原始数据长度(4字节) 文件大小不超过4G 

                //为Data指定byte的长度,故意开大byte数据的范围
                //读取未压缩的原始数据长度
                quartetBuffer = new byte[4];
                long position = sourceStream.Length - 4;
                sourceStream.Position = position;
                sourceStream.Read(quartetBuffer, 0, 4);

                int checkLength = BitConverter.ToInt32(quartetBuffer, 0);
                byte[] data;
                if (checkLength <= sourceStream.Length)
                {
                    data = new byte[Int16.MaxValue];
                }
                else
                {
                    data = new byte[checkLength + 100];
                }
                //每100byte从解压流中读出数据,并将读出的数据Copy到Data byte[]中,这样就完成了对数据的解压
                byte[] buffer = new byte[100];

                sourceStream.Position = 0;

                int offset = 0;
                int total = 0;

                while (true)
                {
                    int bytesRead = decompressedStream.Read(buffer, 0, 100);

                    if (bytesRead == 0)
                        break;

                    buffer.CopyTo(data, offset);

                    offset += bytesRead;
                    total += bytesRead;
                }
                //剔除多余的byte
                byte[] actualdata = new byte[total];

                for (int i = 0; i < total; i++)
                    actualdata[i] = data[i];

                return actualdata;
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("从文件{0}解压数据时发生错误", srcFile), ex);
            }
            finally
            {
                if (sourceStream != null)
                    sourceStream.Close();

                if (decompressedStream != null)
                    decompressedStream.Close();
            }
        }
 

6.小结

压缩,解压都用GZipStream,操作的对象时普通流MemoryStream,不同的是:

压缩是将btye[]型的数据写入GZipStream中,而解压的时候是将GzipStream中的数据写入到byte[]中,并将读出的数据写入到MemoryStream后一次性输出

        压缩到文件与压缩成byte[]不同的是压缩到文件利用到了FileStream将流写到文件,解压Gzip文件,需要根据文件的规则进行:后4位记录未压缩前的长度,根据该长度可以将解压出来的文件存放到稍大的byte[]中

分享到:
评论

相关推荐

    vb.net 利用.net自带的GZipStream压缩或者解压文件的代码,不需要任何第三方控件

    网上很少有用VB写的压缩文件的代码,但是,在网络传输,文件下载,打包发布等等方面的需求又比较多,所以,借鉴了一下C#代码的例子,改造成了VB用的类。另外加上了多层文件夹压缩解压。但是,因为时间有限,只是将...

    如何压缩多个文件\文件夹(GZipStream and C#)

    在.Net Framework 2.0 中添加了System.IO.Compression 类来实现对文件/文件夹的压缩/解压(GZipStream方法),包括文档,代码,类文件

    GZipStream压缩文件称gzip格式

    支持同时压缩多文件,可以选择压缩后的文件放置的位置。

    asp.net在线压缩文件

    网络传输文件过程中,如果文件过大将会影响文件传送的效果和速度,如果将文件压缩之后再上传,不但可以...本实例通过asp.net web应用程序中实现了文件的在线压缩功能。 本实例主要使用了FileStream类和GZipStream类。

    C#使用GZipStream解压缩数据文件的方法

    主要介绍了C#使用GZipStream解压缩数据文件的方法,实例分析了C#中GZipStream方法的原理与使用技巧,需要的朋友可以参考下

    序列化和Zip压缩

    本dll提供了两种压缩方式,GZipStream和DeflateStream,在使用Webservice作为服务端的系统中,提高传输性能是比较关键的,而提高传输性能,对传输数据进行压缩是很重要的方法。 使用.Net自带压缩算法,压缩率很大...

    C++ 压缩解压缩库

    C++ 压缩解压缩库,VS2012版本。我只封装了解压缩库,如果需要可以自己封装下压缩的。代码齐全。

    C#使用GZipStream实现文件的压缩与解压

    主要为大家详细介绍了C#使用GZipStream实现文件的压缩与解压,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    用.NET 2.0压缩/解压功能处理大型数据

    这个新名称空间提供了两个数据压缩类:DeflateStream和GZipStream。这两个压缩类都支持无损压缩和解压,其设计目的是为了处理流式数据的压缩和解压问题。压缩是减少数据大小的有效办法。例如,如果你有巨大量的数据...

    C#实现GZip压缩和解压缩入门实例

    主要是因为GZipStream的构造函数中第一个需要传入一个Stream,第二个是指定操作方式:压缩还是解压缩。 当时的疑问点主要有: 1.我传入的Stream是包含未压缩数据的Stream吗?2.我解压时是从一个压缩流中读取数据后再...

    Asp.net使用HttpModule压缩并删除空白Html请求的实现代码

    让我们先来实现压缩与删除空白类, 继承自Stream类: 代码如下: /// &lt;summary&gt; /// CompressWhitespaceFilter /// &lt;/summary&gt; public class CompressWhitespaceFilter : Stream { private GZipStream _...

    c# 压缩及解压缩源码

    压缩及解压缩

    【.Net 】Zip操作库

    DotNetZip是一个易于使用,快速,自由操纵类库和工具集压缩文件或文件夹。 zip和解压很简单:与DotNetZip。NET中编写的应用程序在VB,C#中 - 任何。NET语言 - 可以轻松地创建,阅读,摘录,或更新压缩文件。对于单...

    RichEdit控件

    鉴于有朋友说差组件,我需要在说明一下,差的是一个压缩模块,此模块用的就是.net里面的GZipStream封装的,用于压缩Data,可以自己写,也可以去掉。 C#的RichTextBox控件,使用的是RichEdit50(系统写字板所使用的控件...

    gzipstream:gzipstream允许Python处理来自流媒体源的多部分gzip文件-python source file

    作为用法的示例, examples/streaming_commoncrawl_from_s3.py显示了如何使用gzipstream增量处理gzip压缩的Web存档(WARC)文件。 该文件的大小几乎为1 GB,是从2014-15 Common Crawl数据集中随机选择的,并托管在...

    .net压缩功能实现方法

    代码如下:public static class Compressor { public static byte[] Compress(byte[] data) { using (MemoryStream output = new MemoryStream()) { using (GZipStream gzip = new GZipStream(output, ...

    压缩解压数据 dll

    c++ 调用 gzipstream 对数据进行加压或者解压

Global site tag (gtag.js) - Google Analytics