using System.IO.Compression;
using System.Text;
public static class StringExtension
{
#region 数据压缩
///
/// 压缩字符串
///
///
///
public static string CompressByUTF8(string input)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] result = Compress(inputBytes);
return Convert.ToBase64String(result);
}
///
/// 压缩字符串
///
///
///
public static string Compress(string input)
{
byte[] inputBytes = Encoding.Default.GetBytes(input);
byte[] result = Compress(inputBytes);
return Convert.ToBase64String(result);
}
///
/// 解压缩字符串
///
///
///
public static string Decompress(string input)
{
byte[] inputBytes = Convert.FromBase64String(input);
byte[] depressBytes = Decompress(inputBytes);
return Encoding.Default.GetString(depressBytes);
}
///
/// 压缩字节数组
///
///
public static byte[] Compress(byte[] inputBytes)
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress, true))
{
zipStream.Write(inputBytes, 0, inputBytes.Length);
zipStream.Close(); //很重要,必须关闭,否则无法正确解压
return outStream.ToArray();
}
}
}
///
/// 解压缩字节数组
///
///
public static byte[] Decompress(byte[] inputBytes)
{
using (MemoryStream inputStream = new MemoryStream(inputBytes))
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
zipStream.CopyTo(outStream);
zipStream.Close();
return outStream.ToArray();
}
}
}
}
#endregion
}