SoftZipped.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Text;
  7. namespace HslCommunication.BasicFramework
  8. {
  9. /// <summary>
  10. /// 一个负责压缩解压数据字节的类
  11. /// </summary>
  12. public class SoftZipped
  13. {
  14. // 压缩字节
  15. // 1.创建压缩的数据流
  16. // 2.设定compressStream为存放被压缩的文件流,并设定为压缩模式
  17. // 3.将需要压缩的字节写到被压缩的文件流
  18. /// <summary>
  19. /// 压缩字节数据
  20. /// </summary>
  21. /// <param name="bytes">等待被压缩的数据</param>
  22. /// <exception cref="ArgumentNullException"></exception>
  23. /// <returns>压缩之后的字节数据</returns>
  24. public static byte[] CompressBytes(byte[] bytes)
  25. {
  26. if (bytes == null) throw new ArgumentNullException("bytes");
  27. using (MemoryStream compressStream = new MemoryStream())
  28. {
  29. using (var zipStream = new GZipStream(compressStream, CompressionMode.Compress))
  30. zipStream.Write(bytes, 0, bytes.Length);
  31. return compressStream.ToArray();
  32. }
  33. }
  34. // 解压缩字节
  35. // 1.创建被压缩的数据流
  36. // 2.创建zipStream对象,并传入解压的文件流
  37. // 3.创建目标流
  38. // 4.zipStream拷贝到目标流
  39. // 5.返回目标流输出字节
  40. /// <summary>
  41. /// 解压压缩后的数据
  42. /// </summary>
  43. /// <param name="bytes">压缩后的数据</param>
  44. /// <exception cref="ArgumentNullException"></exception>
  45. /// <returns>压缩前的原始字节数据</returns>
  46. public static byte[] Decompress(byte[] bytes)
  47. {
  48. if (bytes == null) throw new ArgumentNullException("bytes");
  49. using (var compressStream = new MemoryStream(bytes))
  50. {
  51. using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress))
  52. {
  53. using (var resultStream = new MemoryStream())
  54. {
  55. int readLength = 1024;
  56. byte[] buf = new byte[readLength];
  57. int len = 0;
  58. while ((len = zipStream.Read(buf, 0, readLength)) > 0)
  59. {
  60. resultStream.Write(buf, 0, len);
  61. }
  62. return resultStream.ToArray();
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }