要知道字符串的“大小”(以 kb 为单位),我们需要知道编码。如果我们假设 UTF8,那么它(不包括 BOM 等)如下所示(但如果不是 UTF8,则交换编码):
int len = Encoding.UTF8.GetByteCount(longString);
重新包装;我建议通过 UTF8 进行 GZIP,如果必须是字符串,可以选择后跟 base-64:
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
{
byte[] raw = Encoding.UTF8.GetBytes(longString);
gzip.Write(raw, 0, raw.Length);
gzip.Close();
}
byte[] zipped = ms.ToArray(); // as a BLOB
string base64 = Convert.ToBase64String(zipped); // as a string
// store zipped or base64
}