如何确定字符串的大小,并压缩它

时间:2010-05-04 11:27:21

标签: c# string amazon-sqs

我目前正在使用Amazon SQS在C#中开发一个应用程序 邮件的大小限制为8kb。

我的方法类似于:

public void QueueMessage(string message)

在这个方法中,我首先要压缩消息(大多数消息都以json的形式传递,所以已经很小了)

如果压缩的字符串仍大于8kb,我会将其存储在S3中。

我的问题是:

如何轻松测试字符串的大小,以及压缩字符串的最佳方法是什么? 我不是在寻求大规模缩小,只是简单易用 - 并且易于解压缩另一端。

2 个答案:

答案 0 :(得分:12)

要知道字符串的“大小”(以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
    }

答案 1 :(得分:1)

给这个函数提供解压缩字节。我能想出的最好的是

public static byte[] ZipToUnzipBytes(byte[] bytesContext)
        {
            byte[] arrUnZipFile = null;
            if (bytesContext.Length > 100)
            {
                using (var inFile = new MemoryStream(bytesContext))
                {
                    using (var decompress = new GZipStream(inFile, CompressionMode.Decompress, false))
                    {
                        byte[] bufferWrite = new byte[4];
                        inFile.Position = (int)inFile.Length - 4;
                        inFile.Read(bufferWrite, 0, 4);
                        inFile.Position = 0;
                        arrUnZipFile = new byte[BitConverter.ToInt32(bufferWrite, 0) + 100];
                        decompress.Read(arrUnZipFile, 0, arrUnZipFile.Length);
                    }
                }
            }
            return arrUnZipFile;
        }