我正在使用以下代码使用 Gzip 压缩字符串:
public static String Compress(String decompressed)
{
byte[] data = Encoding.Unicode.GetBytes(decompressed);
using (var input = new MemoryStream(data))
using (var output = new MemoryStream())
{
using (var gzip = new GZipStream(output, CompressionMode.Compress, true))
{
input.CopyTo(gzip);
}
return Convert.ToBase64String(output.ToArray());
}
}
并使用以下代码对其进行解压缩:
public static String Decompress(String compressed)
{
byte[] data = Convert.FromBase64String(compressed);
using (MemoryStream input = new MemoryStream(data))
using (GZipStream gzip = new GZipStream(input, CompressionMode.Decompress))
using (MemoryStream output = new MemoryStream())
{
gzip.CopyTo(output);
StringBuilder sb = new StringBuilder();
foreach (byte b in output.ToArray())
sb.Append((char)b);
return sb.ToString();
}
}
当我在此示例代码中使用这些函数时,结果只是字母S
:
String test = "SELECT * FROM foods f WHERE f.name = 'chicken';";
String com = Compress(test);
String decom = Decompress(com);
Console.WriteLine(decom);
如果我调试代码,我看到的decom
值为
S\0E\0L\0E\0C\0T\0 \0*\0 \0F\0R\0O\0M\0 \0f\0o\0o\0d\0s\0 \0f\0 \0W\0H\0E\0R\0E\0 \0f\0.\0n\0a\0m\0e\0 \0=\0 \0'\0c\0h\0i\0c\0k\0e\0n\0'\0;\0
但显示的值只是字母S
。