做项目涉及到存入到数据库或者http传输的数据量比较大,这个时候,就需要考虑在存入数据库或者发送传输之前,将数据压缩下,当从数据库中取出时,再解压还原数据。特地找了下发现有GZipStream可以实现这个功能。此类表示gzip数据格式,该格式使用行业标准算法进行无损文件压缩和解压缩。该格式包括用于检测数据损坏的循环冗余校验值。gzip数据格式使用与DeflateStream类相同的算法,但可以扩展为使用其他压缩格式。该格式很容易以专利未涵盖的方式实施。从.NET Framework 4.5开始,DeflateStream类使用zlib库进行压缩。因此,与.NET Framework的早期版本相比,它提供了更好的压缩算法,并且在大多数情况下,提供了较小的压缩文件。) j3 m a! \4 N/ D: ^& }2 a
GZipStream使用的一般流程如下:% }) n# f( g3 p
- 打开一个现有的文件
- 打开/创建输出文件
- 创建GZipStream对象
- 逐字节读源文件,并把它传递到GZipStream
- 使用GZipStream写入到输出文件流
9 o; h1 |3 [2 U- F3 v 代码实现
5 ~- @7 T Y' M- t0 D* N" U1、压缩字符串8 R# B6 W& O$ K
- /// <summary>
- /// 压缩字符串,回传 Base64 结果
- /// </summary>
- /// <param name="text"></param>
- /// <returns></returns>
- public static string ZipText(string text)
- {
- byte[] inputBytes = Encoding.UTF8.GetBytes(text);
- return ZipText(inputBytes);
- }
-
- public static string ZipText(byte[] inputBytes)
- {
- using (MemoryStream outputStream = new MemoryStream())
- {
- using (GZipStream gs = new GZipStream(outputStream, CompressionMode.Compress))
- {
- gs.Write(inputBytes, 0, inputBytes.Length);
- }
-
- byte[] outputBytes = outputStream.ToArray();
- string result = Convert.ToBase64String(outputBytes);
- return result;
- }
- }
2、解压缩字符串
0 c Q, [6 E2 r- l0 P' e$ C! R, V- /// <summary>
- /// 解压缩字符串
- /// </summary>
- /// <param name="zippedText"></param>
- /// <returns></returns>
- public static string UnzipZippedText(string zippedText)
- {
- if (String.IsNullOrEmpty(zippedText))
- {
- return String.Empty;
- }
- string unzipedText = null;
- try
- {
- byte[] buffer = Convert.FromBase64String(zippedText);
- MemoryStream ms = new MemoryStream(buffer);
- GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
-
- using (StreamReader streamReader = new StreamReader(zipStream))
- {
- unzipedText = streamReader.ReadToEnd();
- }
- }
- catch (Exception ex)
- {
- unzipedText = String.Empty;
- }
-
- return unzipedText;
- }
运行结果测试,源文件经过压缩大小只有120字节,而解压后,源文件与解压后txt的大小一致
2 f9 K; O9 q. T3 I( K; {9 i5 i
|