压缩方法
#region 压缩 /// <summary>
/// 压缩
/// </summary>
/// <param name="bytes">未被压缩的字节数据</param>
/// <returns></returns>
public static byte[] Compress(byte[] bytes)
{
if (bytes == null)
return null; using (MemoryStream oStream = new MemoryStream()) //压缩
{
GZipStream zipStream = new GZipStream(oStream, CompressionMode.Compress);
zipStream.Write(bytes, , bytes.Length);
zipStream.Flush();
zipStream.Close(); return oStream.ToArray();
}
} /// <summary>
/// 压缩
/// </summary>
/// <param name="dataOriginal">未被压缩的数据</param>
/// <returns></returns>
public static byte[] Compress(object dataOriginal)
{
if (dataOriginal == null)
return null; byte[] bytes = null;
using (MemoryStream mStream = new MemoryStream()) //序列化成二进制数组
{
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(mStream, dataOriginal);
bytes = mStream.ToArray();
} return Compress(bytes);
} /// <summary>
/// 压缩字符串
/// </summary>
/// <param name="unZipData">未被压缩的数据</param>
/// <returns></returns>
public static string Compress(string unZipData)
{
if (string.IsNullOrEmpty(unZipData))
return null;
var bytes = Compress(unZipData as object);
if (bytes == null)
return null; return Convert.ToBase64String(bytes); //一定要Base64,否则会出错
} #endregion
解压方法
#region 解压缩 /// <summary>
/// 解压缩
/// </summary>
/// <param name="stream">流</param>
/// <returns></returns>
public static object Decompress(Stream stream)
{
stream.Seek(, SeekOrigin.Begin);
GZipStream unZipStream = new GZipStream(stream, CompressionMode.Decompress, true);
object dsResult = null;
BinaryFormatter bFormatter = new BinaryFormatter();
dsResult = bFormatter.Deserialize(unZipStream) as object;
unZipStream.Close(); return dsResult;
} /// <summary>
/// 解压缩
/// </summary>
/// <param name="bytes">压缩后的字节数组</param>
/// <returns></returns>
public static object Decompress(byte[] bytes)
{
if (bytes == null)
return null;
using (MemoryStream mStream = new MemoryStream(bytes))
{
return Decompress(mStream);
} } /// <summary>
/// 解压缩字符串
/// </summary>
/// <param name="zipData">被压缩的字符串</param>
/// <returns></returns>
public static string Decompress(string zipData)
{
if (string.IsNullOrEmpty(zipData))
return null;
var bytes = Convert.FromBase64String(zipData); //一定要Base64,否则会出错 return Decompress(bytes) as string;
} #endregion
字符串压缩、解压缩 字节数组和字符串的相互装换要用Base64编码!