CompressUtil.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Text;
  5. namespace CSharpUtil
  6. {
  7. /// <summary>
  8. /// 压缩工具类
  9. /// </summary>
  10. class CompressUtil
  11. {
  12. /// <summary>
  13. /// 数据最大长度不宜超过1M
  14. /// </summary>
  15. const int MaxDataLenght = 1024 * 1024;
  16. /// <summary>
  17. /// 利用deflate算法压缩字节数组
  18. /// </summary>
  19. /// <param name="data">字节数组(不宜超过1M)</param>
  20. /// <param name="compressMode">压缩模式(压缩/解压)</param>
  21. /// <exception cref="OutOfMemoryException">数据不建议超过1M</exception>
  22. /// <returns></returns>
  23. public static byte[] Deflate(byte[] data, CompressionMode compressMode = CompressionMode.Compress)
  24. {
  25. if (data.Length > MaxDataLenght)
  26. {
  27. throw new OutOfMemoryException("传入的数据过大(不接受超过1M的数据)!");
  28. }
  29. else
  30. {
  31. byte[] buffer = null;
  32. using (MemoryStream outms = new MemoryStream())
  33. {
  34. using (DeflateStream df = new DeflateStream(outms, compressMode, true))
  35. {
  36. df.Write(data, 0, data.Length);
  37. }
  38. outms.Position = 0;
  39. buffer = outms.ToArray();
  40. }
  41. return buffer;
  42. }
  43. }
  44. /// <summary>
  45. /// 解压deflate数据
  46. /// </summary>
  47. /// <param name="data">被压缩的内容</param>
  48. /// <exception cref="OutOfMemoryException">数据不建议超过1M</exception>
  49. /// <returns></returns>
  50. public static byte[] InFlate(byte[] data)
  51. {
  52. // todo: 这种写法在system.io.compress模式下是支持的.
  53. return Deflate(data, CompressionMode.Decompress);
  54. }
  55. public static string InFlate(byte[] data, Encoding encoder)
  56. {
  57. using (MemoryStream inputStream = new MemoryStream(data))
  58. using (DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress))
  59. using (StreamReader reader = new StreamReader(gzip, GlobalConfig.Encoding))
  60. {
  61. return reader.ReadToEnd();
  62. }
  63. }
  64. }
  65. }