.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[]中
- GZipUtil.rar (1.8 KB)
.net 利用 GZipStream 压缩和解压缩的更多相关文章
- 利用ICSharpCode进行压缩和解压缩
说说我利用ICSharpCode进行压缩和解压缩的一些自己的一下实践过程 1:组件下载地址 参考文章:C#使用ICSharpCode.SharpZipLib.dll压缩文件夹和文件 2: 文件类 // ...
- C# 利用ICSharpCode.SharpZipLib.dll 实现压缩和解压缩文件
我们 开发时经常会遇到需要压缩文件的需求,利用C#的开源组件ICSharpCode.SharpZipLib, 就可以很容易的实现压缩和解压缩功能. 压缩文件: /// <summary> ...
- 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...
- 利用SharpZipLib进行字符串的压缩和解压缩
http://www.izhangheng.com/sharpziplib-string-compression-decompression/ 今天搞了一晚上压缩和解压缩问题,java压缩的字符串,用 ...
- C#利用SharpZipLib进行文件的压缩和解压缩
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net下载了关于压缩和解压缩的源码,但是下载下来后,面对这么多的代码,一时不知如何下手.只好耐下心来, ...
- C#- 压缩和解压缩的研究 .
用了第二种方法,感觉很不错,其他都没用过了.摘录下来,做一个备忘. 最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip ...
- .net中压缩和解压缩的处理
最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip 参考代码如下: //======================= ...
- 关于webservice大数据量传输时的压缩和解压缩
当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...
- iOS中使用ZipArchive压缩和解压缩文件-备
为什么我需要解压缩文件 有许多原因能解释为什么我要在工程中使用压缩和解压缩功能,下面是几个常见的原因: 苹果App Store的50M下载限制 苹 果公司出于流量的考虑,规定在非WIFI环境下,限制用 ...
随机推荐
- ns2出现Client: Handoff Attempt的情况解决
找到mac/mac-802_11.cc,这是系统本身一个bug,对于adhoc网络无需进行切换尝试. > if (*rcount == 3 && handoff == 0) {& ...
- C#学习笔记(3)
先理解一下方法重写和方法重载这2个概念: 1.方法重写(override):发生在父子类之间,子类重写父类中的方法,关键字是override. 2.方法重载(overload):一个类中有多个重名的方 ...
- iTerm 使用expect实现自动远程登录,登录跳板机
#!/usr/bin/expect set timeout 10 spawn ssh -p [lindex $argv 0] [lindex $argv 1]@[lindex $argv 2] exp ...
- python+sqlite3
一个小例子, # -*- coding:utf-8 -*- ''' Created on 2015年10月8日 (1.1)Python 2.7 Tutorial Pt 12 SQLite - http ...
- 通过 OpenNI 建立 Kinect 3D Point Cloud
這篇還是算延續前一篇的<透過 OpneNI 合併 Kinect 深度以及彩色影像資料>.在可以透過 OpenNI 讀取到 Kinect 的深度.色彩資訊之後,其實就可以試著用這些資訊,來重 ...
- mac 下 sublime text 运行c++/c 不能使用scanf/cin
{ "cmd": ["g++", "${file}", "-o", "${file_path}/${file_ ...
- How to say all the keyboard symbols in English and Chinese
How to say all the keyboard symbols in English Symbol English 中文 ~ tilde 波浪号 ` grave accent, backquo ...
- The test form is only available for requests from the local machine 解决方法
protocolsdocumentationsoapweb 当您尝试从远程计算机访问 Web 服务时,不会显示“调用”按钮.并且,您会收到以下错误信息: The test form is only ...
- ES6 语法简介
参考: http://es6.ruanyifeng.com/ 总结学习 JavaScript语言下一代标准,2015年6月正式发布. 1.let和const命令 let用作变量声明,只在代码块内有效 ...
- ubuntu下php开发环境搭建,nginx+(cgi)php5fpm+memcached+xdebug
由于只是开发环境,所以都是选择比较简单的apt-get安装方式 ,但中间也遇到一点问题. 首先安装nginx nginx的安装和配置其实很简单,nginx本身非常轻量级, 直接 sudo apt-ge ...