post

C#中利用GZipStream压缩/解压字符串

今天做的项目需要解压GZIP压缩后的字符串,原字符串由JAVA语言压缩的,下面记录下如何用C#中的GZipStream类解压/压缩字符串。

using System.IO;
using System.IO.Compression;

///<summary>
/// GZipStream压缩字符串
/// </summary>
public Stream GZipCompress(string str)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
MemoryStream msReturn;

using (MemoryStream msTemp = new MemoryStream())
{
using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, true))
{
gz.Write(buffer, 0, buffer.Length);
gz.Close();
msReturn = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length);
}
}
return msReturn;
}

///<summary>
/// GZipStream解压字符串
/// </summary>
public string GZipDecompress(Stream stream)
{
byte[] buffer = new byte[100];
int length = 0;

using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
}
return System.Text.Encoding.UTF8.GetString(msTemp.ToArray());
}
}
}

Speak Your Mind

*

· 3,292 次浏览