c# gzip html,C# 使用GZip对字符串压缩和解压

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.IO;6 usingSystem.IO.Compression;7 usingSystem.Data;8

9 namespaceDemo10 {11 public classZipHelper12 {13 ///

14 ///解压15 ///

16 ///

17 ///

18 public static DataSet GetDatasetByString(stringValue)19 {20 DataSet ds = newDataSet();21 string CC =GZipDecompressString(Value);22 System.IO.StringReader Sr = newStringReader(CC);23 ds.ReadXml(Sr);24 returnds;25 }26 ///

27 ///根据DATASET压缩字符串28 ///

29 ///

30 ///

31 public static string GetStringByDataset(stringds)32 {33 returnGZipCompressString(ds);34 }35 ///

36 ///将传入字符串以GZip算法压缩后,返回Base64编码字符37 ///

38 /// 需要压缩的字符串

39 /// 压缩后的Base64编码的字符串

40 public static string GZipCompressString(stringrawString)41 {42 if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)43 {44 return "";45 }46 else

47 {48 byte[] rawData =System.Text.Encoding.UTF8.GetBytes(rawString.ToString());49 byte[] zippedData =Compress(rawData);50 return (string)(Convert.ToBase64String(zippedData));51 }52

53 }54 ///

55 ///GZip压缩56 ///

57 ///

58 ///

59 public static byte[] Compress(byte[] rawData)60 {61 MemoryStream ms = newMemoryStream();62 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);63 compressedzipStream.Write(rawData, 0, rawData.Length);64 compressedzipStream.Close();65 returnms.ToArray();66 }67 ///

68 ///将传入的二进制字符串资料以GZip算法解压缩69 ///

70 /// 经GZip压缩后的二进制字符串

71 /// 原始未压缩字符串

72 public static string GZipDecompressString(stringzippedString)73 {74 if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)75 {76 return "";77 }78 else

79 {80 byte[] zippedData =Convert.FromBase64String(zippedString.ToString());81 return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));82 }83 }84 ///

85 ///ZIP解压86 ///

87 ///

88 ///

89 public static byte[] Decompress(byte[] zippedData)90 {91 MemoryStream ms = newMemoryStream(zippedData);92 GZipStream compressedzipStream = newGZipStream(ms, CompressionMode.Decompress);93 MemoryStream outBuffer = newMemoryStream();94 byte[] block = new byte[1024];95 while (true)96 {97 int bytesRead = compressedzipStream.Read(block, 0, block.Length);98 if (bytesRead <= 0)99 break;100 else

101 outBuffer.Write(block, 0, bytesRead);102 }103 compressedzipStream.Close();104 returnoutBuffer.ToArray();105 }106 }107 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值