我们经常将存在数据库的字符串压缩一下,然后再将压缩的信息存入数据库,以减少数据库的存取空间,那么下面就是我们压缩信息与解压的信息的方法。
//压缩字符串的方法
public string StringCompress(string duzhan)
{
byte[] bytData = System.Text.Encoding.Unicode.GetBytes(duzhan);
MemoryStream ms = new MemoryStream();
Stream s = new GZipStream(ms, CompressionMode.Compress);
s.Write(bytData, 0, bytData.Length);
s.Close();
byte[] dataCompressed = (byte[])ms.ToArray();
return System.Convert.ToBase64String(dataCompressed, 0, dataCompressed.Length);
}
//解压字符串的方法
public string StringDeCompress(string duzhan)
{
System.Text.StringBuilder strUncompressed = new System.Text.StringBuilder();
int totalLength = 0;
byte[] bInput = System.Convert.FromBase64String(duzhan); ;
byte[] dataWrite = new byte[4096];
Stream s = new GZipStream(new MemoryStream(bInput), CompressionMode.Decompress);
while (true)
{
int size = s.Read(dataWrite, 0, dataWrite.Length);
if (size > 0)
{
totalLength += size;
strUncompressed.Append(System.Text.Encoding.Unicode.GetString(dataWrite, 0, size));
}
else
{
break;
}
}
s.Close();
return strUncompressed.ToString();
}
如有不懂,联系利来w66(中国)有限公司(//labelmachines.net)