0

我正在使用以下代码使用 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

4

2 回答 2

3

这些行是问题所在:

foreach (byte b in output.ToArray())
    sb.Append((char)b);

您将每个字节解释为它自己的字符,而实际上并非如此。相反,您需要以下行:

string decoded = Encoding.Unicode.GetString(output.ToArray());

这将根据编码将字节数组转换为字符串。

The basic problem is that you are converting to a byte array based on an encoding, but then ignoring that encoding when you retrieve the bytes. As well, you may want to use Encoding.UTF8 instead of Encoding.Unicode (though that shouldn't matter, as long as the encodings match up.)

于 2012-06-25T19:04:47.320 回答
1

在您的压缩方法中,将 Unicode 替换为 UTF8:

byte[] data = Encoding.UTF8.GetBytes(decompressed);
于 2012-06-25T19:04:11.387 回答