C# GZip对字符串压缩和解压

     /// <summary>
/// 压缩方法
/// </summary>
public static string CompressString(string str)
{
string compressString = "";
byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
byte[] compressAfterByte = Compress(compressBeforeByte);
compressString = Convert.ToBase64String(compressAfterByte);
return compressString;
} public static byte[] Compress(byte[] data)
{
try
{
MemoryStream ms = new MemoryStream();
GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
zip.Write(data, , data.Length);
zip.Close();
byte[] buffer = new byte[ms.Length];
ms.Position = ;
ms.Read(buffer, , buffer.Length);
ms.Close();
return buffer; }
catch (Exception e)
{
throw new Exception(e.Message);
}
} /// <summary>
/// 字符串解压缩
/// </summary>
public static string DecompressString(string str)
{
string compressString = "";
byte[] compressBeforeByte = Convert.FromBase64String(str);
byte[] compressAfterByte = Decompress(compressBeforeByte);
compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
return compressString;
} public static byte[] Decompress(byte[] data)
{
try
{
MemoryStream ms = new MemoryStream(data);
GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
MemoryStream msreader = new MemoryStream();
byte[] buffer = new byte[0x1000];
while (true)
{
int reader = zip.Read(buffer, , buffer.Length);
if (reader <= )
{
break;
}
msreader.Write(buffer, , reader);
}
zip.Close();
ms.Close();
msreader.Position = ;
buffer = msreader.ToArray();
msreader.Close();
return buffer;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
上一篇:使用Astah画UML类图经验总结


下一篇:Unity游戏内版本更新