做项目涉及到存入到数据库或者http传输的数据量比较大,这个时候,就需要考虑在存入数据库或者发送传输之前,将数据压缩下,当从数据库中取出时,再解压还原数据。特地找了下发现有GZipStream可以实现这个功能。此类表示gzip数据格式,该格式使用行业标准算法进行无损文件压缩和解压缩。该格式包括用于检测数据损坏的循环冗余校验值。gzip数据格式使用与DeflateStream类相同的算法,但可以扩展为使用其他压缩格式。该格式很容易以专利未涵盖的方式实施。从.NET Framework 4.5开始,DeflateStream类使用zlib库进行压缩。因此,与.NET Framework的早期版本相比,它提供了更好的压缩算法,并且在大多数情况下,提供了较小的压缩文件。3 A9 H" N: f# w3 U1 t; b* L9 D# K
GZipStream使用的一般流程如下:6 ~' l9 y0 ^) }* V3 t
- 打开一个现有的文件
- 打开/创建输出文件
- 创建GZipStream对象
- 逐字节读源文件,并把它传递到GZipStream
- 使用GZipStream写入到输出文件流
% t6 f/ Q0 ~8 o: x/ l 代码实现2 Q Z, V) _ d% Z6 x
1、压缩字符串4 A9 |/ L" U3 G( t7 Q
/// <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、解压缩字符串
5 i3 W8 W) j, I9 q6 }/ F( C /// <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的大小一致
7 e/ x* a6 V( h0 H" C3 B: i; r9 r
|