纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.3 KiB

3 years ago
  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 NFine.Code
  8. {
  9. public class GZip
  10. {
  11. /// <summary>
  12. /// 压缩
  13. /// </summary>
  14. /// <param name="text">文本</param>
  15. public static string Compress(string text)
  16. {
  17. if (text.IsEmpty())
  18. return string.Empty;
  19. byte[] buffer = Encoding.UTF8.GetBytes(text);
  20. return Convert.ToBase64String(Compress(buffer));
  21. }
  22. /// <summary>
  23. /// 解压缩
  24. /// </summary>
  25. /// <param name="text">文本</param>
  26. public static string Decompress(string text)
  27. {
  28. if (text.IsEmpty())
  29. return string.Empty;
  30. byte[] buffer = Convert.FromBase64String(text);
  31. using (var ms = new MemoryStream(buffer))
  32. {
  33. using (var zip = new GZipStream(ms, CompressionMode.Decompress))
  34. {
  35. using (var reader = new StreamReader(zip))
  36. {
  37. return reader.ReadToEnd();
  38. }
  39. }
  40. }
  41. }
  42. /// <summary>
  43. /// 压缩
  44. /// </summary>
  45. /// <param name="buffer">字节流</param>
  46. public static byte[] Compress(byte[] buffer)
  47. {
  48. if (buffer == null)
  49. return null;
  50. using (var ms = new MemoryStream())
  51. {
  52. using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
  53. {
  54. zip.Write(buffer, 0, buffer.Length);
  55. }
  56. return ms.ToArray();
  57. }
  58. }
  59. /// <summary>
  60. /// 解压缩
  61. /// </summary>
  62. /// <param name="buffer">字节流</param>
  63. public static byte[] Decompress(byte[] buffer)
  64. {
  65. if (buffer == null)
  66. return null;
  67. return Decompress(new MemoryStream(buffer));
  68. }
  69. /// <summary>
  70. /// 压缩
  71. /// </summary>
  72. /// <param name="stream">流</param>
  73. public static byte[] Compress(Stream stream)
  74. {
  75. if (stream == null || stream.Length == 0)
  76. return null;
  77. return Compress(StreamToBytes(stream));
  78. }
  79. /// <summary>
  80. /// 解压缩
  81. /// </summary>
  82. /// <param name="stream">流</param>
  83. public static byte[] Decompress(Stream stream)
  84. {
  85. if (stream == null || stream.Length == 0)
  86. return null;
  87. using (var zip = new GZipStream(stream, CompressionMode.Decompress))
  88. {
  89. using (var reader = new StreamReader(zip))
  90. {
  91. return Encoding.UTF8.GetBytes(reader.ReadToEnd());
  92. }
  93. }
  94. }
  95. /// <summary>
  96. /// 流转换为字节流
  97. /// </summary>
  98. /// <param name="stream">流</param>
  99. public static byte[] StreamToBytes(Stream stream)
  100. {
  101. stream.Seek(0, SeekOrigin.Begin);
  102. var buffer = new byte[stream.Length];
  103. stream.Read(buffer, 0, buffer.Length);
  104. return buffer;
  105. }
  106. }
  107. }