HttpGzip.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.IO;
  2. using System.IO.Compression;
  3. using System.Text;
  4. namespace IFramework.Net.Http
  5. {
  6. public class HttpGzip
  7. {
  8. public static string UnzipToString(byte[] content, string encoding = "UTF-8")
  9. {
  10. using (GZipStream deStream = new GZipStream(new MemoryStream(content), CompressionMode.Decompress))
  11. using (StreamReader reader = new StreamReader(deStream, Encoding.GetEncoding(encoding)))
  12. {
  13. string result = reader.ReadToEnd();
  14. return result;
  15. }
  16. }
  17. public static byte[] UnzipToBytes(byte[] content)
  18. {
  19. using (GZipStream deStream = new GZipStream(new MemoryStream(content), CompressionMode.Decompress))
  20. using (MemoryStream ms = new MemoryStream())
  21. {
  22. deStream.CopyTo(ms);
  23. return ms.ToArray();
  24. }
  25. }
  26. public static byte[] ZipToBytes(byte[] content)
  27. {
  28. using(MemoryStream ms=new MemoryStream())
  29. using (GZipStream ComStream = new GZipStream(ms, CompressionMode.Compress))
  30. {
  31. ComStream.Write(content, 0, content.Length);
  32. return ms.ToArray();
  33. }
  34. }
  35. public static byte[] ZipToBytes(string content,string encoding="UTF-8")
  36. {
  37. using (MemoryStream ms = new MemoryStream())
  38. using (GZipStream ComStream = new GZipStream(ms, CompressionMode.Compress))
  39. {
  40. byte[] buf = Encoding.GetEncoding(encoding).GetBytes(content);
  41. ComStream.Write(buf, 0, buf.Length);
  42. return ms.ToArray();
  43. }
  44. }
  45. }
  46. }