标题:C#压缩和解压缩字节(GZip的使用)

作用:此类在 .NET Framework 2.0 版中是新增的。提供用于压缩和解压缩流的方法和属性。
定义:表示 GZip 数据格式,它使用无损压缩和解压缩文件的行业标准算法。这种格式包括一个检测数据损坏的循环冗余校验值。GZip 数据格式使用的算法与 DeflateStream 类的算法相同,但它可以扩展以使用其他压缩格式。这种格式可以通过不涉及专利使用权的方式轻松实现。gzip 的格式可以从 RFC 1952“GZIP file format specification 4.3(GZIP 文件格式规范 4.3)GZIP file format specification 4.3(GZIP 文件格式规范 4.3)”中获得。此类不能用于压缩大于 4 GB 的文件。

下面给出两个具体Demo:
实例1

  1. //压缩字节
  2. //1.创建压缩的数据流
  3. //2.设定compressStream为存放被压缩的文件流,并设定为压缩模式
  4. //3.将需要压缩的字节写到被压缩的文件流
  5. public static byte[] CompressBytes(byte[] bytes)
  6. {
  7. using(MemoryStream compressStream = new MemoryStream())
  8. {
  9. using(var zipStream = new GZipStream(compressStream, CompressMode.ComPress))
  10. zipStream.Write(bytes, , bytes.Length);
  11. return compressStream.ToArray();
  12. }
  13. }
  14. //解压缩字节
  15. //1.创建被压缩的数据流
  16. //2.创建zipStream对象,并传入解压的文件流
  17. //3.创建目标流
  18. //4.zipStream拷贝到目标流
  19. //5.返回目标流输出字节
  20. public static byte[] Decompress(byte[] bytes)
  21. {
  22. using(var compressStream = new MemoryStream(bytes))
  23. {
  24. using(var zipStream = new GZipStream(compressStream, CompressMode.DeCompress))
  25. {
  26. using(var resultStream = new MemoryStream())
  27. {
  28. zipStream.CopyTo(resultStream);
  29. return resultStream.ToArray();
  30. }
  31. }
  32. }
  33. }

实例2(摘自MSDN):

  1. class Program
  2. {
  3. public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
  4. {
  5. int offset = ;
  6. int totalCount = ;
  7. while (true)
  8. {
  9. int bytesRead = stream.Read(buffer, offset, );
  10. if (bytesRead == )
  11. {
  12. break;
  13. }
  14. offset += bytesRead;
  15. totalCount += bytesRead;
  16. }
  17. return totalCount;
  18. }
  19.  
  20. public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
  21. {
  22. if (len1 != len2)
  23. {
  24. Console.WriteLine("Number of bytes in two buffer are diffreent {0}:{1}", len1, len2);
  25. return false;
  26. }
  27. for (int i = ; i < len1; i++)
  28. {
  29. if (buf1[i] != buf2[i])
  30. {
  31. Console.WriteLine("byte {0} is different {1}{2}", i, buf1[i], buf2[i]);
  32. return false;
  33. }
  34. }
  35. Console.WriteLine("All byte compare true");
  36. return true;
  37. }
  38.  
  39. public static void GZipCompressDecompress(string fileName)
  40. {
  41. Console.WriteLine("Test compresssion and decompression on file {0}", fileName);
  42. FileStream infile;
  43. try
  44. {
  45. //Comopress
  46. infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
  47. byte[] buffer = new byte[infile.Length];
  48. int count = infile.Read(buffer, , buffer.Length);
  49. if (count != buffer.Length)
  50. {
  51. infile.Close();
  52. infile.Dispose();
  53. Console.WriteLine("Test Failed: Unable to read data from file");
  54. return;
  55. }
  56. infile.Close();
  57. MemoryStream ms = new MemoryStream();
  58. GZipStream compressGZipStream = new GZipStream(ms, CompressionMode.Compress, true);
  59. Console.WriteLine("Compression");
  60. compressGZipStream.Write(buffer, , buffer.Length); //从指定字节数组中将压缩的字节写入基础流
  61. compressGZipStream.Close();
  62. Console.WriteLine("Original size:{0}, Compressed size:{1}", buffer.Length, ms.ToArray().Length);
  63.  
  64. //DeCompress
  65. ms.Position = ;
  66. GZipStream deCompressGZipStream = new GZipStream(ms, CompressionMode.Decompress);
  67. Console.WriteLine("Decompression");
  68. byte[] decompressedBuffer = new byte[buffer.Length + ];
  69.  
  70. int totalCount = ReadAllBytesFromStream(deCompressGZipStream, decompressedBuffer);
  71. Console.WriteLine("Decompressed {0} bytes", totalCount);
  72.  
  73. if (!CompareData(buffer, buffer.Length, decompressedBuffer, decompressedBuffer.Length))
  74. {
  75. Console.WriteLine("Error. The two buffers did not compare.");
  76. }
  77. deCompressGZipStream.Dispose();
  78. }
  79. catch (ArgumentNullException)
  80. {
  81. Console.WriteLine("ArgumentNullException:{0}", "Error: The path is null.");
  82. }
  83. catch (ArgumentException)
  84. {
  85. Console.WriteLine("ArgumentException:{0}", "Error: path is a zero-length string, contains an empty string or one more invlaid characters");
  86. }
  87. catch (NotSupportedException)
  88. {
  89. Console.WriteLine("NotSupportedException:{0}", "Cite no file, such as 'con:'、'com1'、'lpt1' in NTFS");
  90. }
  91. catch (FileNotFoundException)
  92. {
  93. Console.WriteLine("FileNotFoundException:{0]", "Find no file");
  94. }
  95. catch (IOException)
  96. {
  97. Console.WriteLine("IOException:{0}", "Occur I/O error");
  98. }
  99. catch (System.Security.SecurityException)
  100. {
  101. Console.WriteLine("System.Security.SecurityException{0}:", "The calls has no permission");
  102. }
  103. catch (UnauthorizedAccessException)
  104. {
  105. Console.WriteLine("UnauthorizedAccessException:{0}", "path specified a file that is read-only, the path is a directory, " +
  106. "or caller does not have the required permissions");
  107. }
  108. }
  109.  
  110. static void Main(string[] args)
  111. {
  112. GZipCompressDecompress(@"D:\config.ini");
  113. }
  114. }

C#压缩和解压缩字节(GZip)的更多相关文章

  1. Linux下的压缩和解压缩命令——gzip/gunzip

    gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...

  2. java工具类——java将一串数据按照gzip方式压缩和解压缩

    我要整理在工作中用到的工具类分享出来,也方便自己以后查阅使用,这些工具类都是我自己实际工作中使用的 import java.io.ByteArrayInputStream; import java.i ...

  3. Linux下的压缩和解压缩命令gzip/gunzip

    作者:邓聪聪 Linux下的压缩和解压缩命令——gzip/gunzip yum -y install zip gzip (--安装压缩工具) gzip命令 gzip命令用来压缩文件.gzip是个使用广 ...

  4. .net 利用 GZipStream 压缩和解压缩

    1.GZipStream 类 此类在 .NET Framework 2.0 版中是新增的. 提供用于压缩和解压缩流的方法和属性 2.压缩byte[] /// <summary> /// 压 ...

  5. 使用commons-compress操作zip文件(压缩和解压缩)

    http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...

  6. 利用SharpZipLib进行字符串的压缩和解压缩

    http://www.izhangheng.com/sharpziplib-string-compression-decompression/ 今天搞了一晚上压缩和解压缩问题,java压缩的字符串,用 ...

  7. Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)

    1.压缩和解压缩命令    常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令        zip 压缩文件名 源文件:压缩文件   ...

  8. 关于webservice大数据量传输时的压缩和解压缩

    当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...

  9. 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...

随机推荐

  1. mac下安装postgreSql

    在 mac 下,可以利用 homebrew 直接安装 PostgreSQL: 1 brew install postgresql -v 稍等片刻,PostgreSQL 就安装完成.接下来就是初始数据库 ...

  2. 网易NAPM Andorid SDK实现原理--转

    原文地址:https://neyoufan.github.io/2017/03/10/android/NAPM%20Android%20SDK/ NAPM 是网易的应用性能管理平台,采用非侵入的方式获 ...

  3. PHP 环境搭建工具

    PHP环境搭建工具 一键集成工具 直接安装后部署到相关目录即可浏览 phpStudy 下载地址:https://pan.baidu.com/s/1i6C3Ph7

  4. 截图 gif 图小工具

    GifCam gyazo gyazo.com Windows 10 中的内置截屏(Win+G)

  5. jsp+jdbc实现用户登录

    1.1 创建数据库表 表名:user 字段: userid   保存用户的登录id name     用户名 password 密码 1.2 实现思路 a. 用户登录,则需要有个一个表单页,此页面可输 ...

  6. python3三级菜单的访问,并按q退出

    #/usr/bin/env python#yehui'''作业三:多级菜单 三级菜单 可依次选择进入各子菜单 所需新知识点:列表.字典'''import readlineclass MultiLeve ...

  7. 关于samsung连接BLE设备的一些资料汇总和开发过程一些经验总结

    1 忙了这么久,终于有时间把最近几个月弄的东西整理一下,顺便我的开发过程和经历. 被公司分到做一个蓝牙4.0的项目,对这种软硬结合的东西也比较感兴趣,所以很快投入到android蓝牙4.0的项目中来. ...

  8. StringUtils 的填充方法

    注意:两个参数的用空格填充,三个参数的用后面的参数填充 第一个参数要填充的字符串,第二个是需要的长度,第三个是以什么填充. 左侧填充: leftPad(): StringUtils.leftPad(S ...

  9. 常用js方法封装

    常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...

  10. 【转】 c#中两个DateTimePicker,一个时间设置为0:0:0,另一个设置为23:59:59

    [转] c#中两个DateTimePicker,一个时间设置为0:0:0,另一个设置为23:59:59 stp1为第一个DateTimePicker this.dtp1.Value=this.dtp1 ...