StringExtension.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.IO.Compression;
  2. using System.Text;
  3. public static class StringExtension
  4. {
  5. #region 数据压缩
  6. /// <summary>
  7. /// 压缩字符串
  8. /// </summary>
  9. /// <param name="input"></param>
  10. /// <returns></returns>
  11. public static string CompressByUTF8(string input)
  12. {
  13. byte[] inputBytes = Encoding.UTF8.GetBytes(input);
  14. byte[] result = Compress(inputBytes);
  15. return Convert.ToBase64String(result);
  16. }
  17. /// <summary>
  18. /// 压缩字符串
  19. /// </summary>
  20. /// <param name="input"></param>
  21. /// <returns></returns>
  22. public static string Compress(string input)
  23. {
  24. byte[] inputBytes = Encoding.Default.GetBytes(input);
  25. byte[] result = Compress(inputBytes);
  26. return Convert.ToBase64String(result);
  27. }
  28. /// <summary>
  29. /// 解压缩字符串
  30. /// </summary>
  31. /// <param name="input"></param>
  32. /// <returns></returns>
  33. public static string Decompress(string input)
  34. {
  35. byte[] inputBytes = Convert.FromBase64String(input);
  36. byte[] depressBytes = Decompress(inputBytes);
  37. return Encoding.Default.GetString(depressBytes);
  38. }
  39. /// <summary>
  40. /// 压缩字节数组
  41. /// </summary>
  42. /// <param name="str"></param>
  43. public static byte[] Compress(byte[] inputBytes)
  44. {
  45. using (MemoryStream outStream = new MemoryStream())
  46. {
  47. using (GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress, true))
  48. {
  49. zipStream.Write(inputBytes, 0, inputBytes.Length);
  50. zipStream.Close(); //很重要,必须关闭,否则无法正确解压
  51. return outStream.ToArray();
  52. }
  53. }
  54. }
  55. /// <summary>
  56. /// 解压缩字节数组
  57. /// </summary>
  58. /// <param name="str"></param>
  59. public static byte[] Decompress(byte[] inputBytes)
  60. {
  61. using (MemoryStream inputStream = new MemoryStream(inputBytes))
  62. {
  63. using (MemoryStream outStream = new MemoryStream())
  64. {
  65. using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.Decompress))
  66. {
  67. zipStream.CopyTo(outStream);
  68. zipStream.Close();
  69. return outStream.ToArray();
  70. }
  71. }
  72. }
  73. }
  74. #endregion
  75. }