做项目涉及到存入到数据库或者http传输的数据量比较大,这个时候,就需要考虑在存入数据库或者发送传输之前,将数据压缩下,当从数据库中取出时,再解压还原数据。特地找了下发现有GZipStream可以实现这个功能。此类表示gzip数据格式,该格式使用行业标准算法进行无损文件压缩和解压缩。该格式包括用于检测数据损坏的循环冗余校验值。gzip数据格式使用与DeflateStream类相同的算法,但可以扩展为使用其他压缩格式。该格式很容易以专利未涵盖的方式实施。从.NET Framework 4.5开始,DeflateStream类使用zlib库进行压缩。因此,与.NET Framework的早期版本相比,它提供了更好的压缩算法,并且在大多数情况下,提供了较小的压缩文件。. T/ G" x8 B9 i* G
GZipStream使用的一般流程如下:
, ^2 {8 v- m' H2 N" ]- 打开一个现有的文件
- 打开/创建输出文件
- 创建GZipStream对象
- 逐字节读源文件,并把它传递到GZipStream
- 使用GZipStream写入到输出文件流
( B6 W/ h9 _1 [/ c! \# {0 f9 d. P 代码实现
* |- K2 v6 H/ |. w0 Y+ E1、压缩字符串4 U# @* m- b# c
/// <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、解压缩字符串$ j1 A, ~ L2 [; C9 L
/// <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的大小一致
+ U5 H) j. i" p) i# M Y- G; s
|