我只是在查看压缩字符串的代码示例。我发现使用GZipStream类就足够了。但我不明白为什么我们必须将它转换为base 64字符串,如示例所示。
using System.IO.Compression;
using System.Text;
using System.IO;
public static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String (gzBuffer);
}
此外,我不明白我的gzBuffer被初始化为compressed.Length + 4
大小。其实我不明白为什么我们也有最后几个陈述。有人可以分享一些亮点......
答案 0 :(得分:3)