如何确定串的大小,并压缩它 [英] How to determine size of string, and compress it

查看:191
本文介绍了如何确定串的大小,并压缩它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发中,使用亚马逊SQS
的大小限制的消息C#应用程序是。8KB

I'm currently developing an application in C# that uses Amazon SQS The size limit for a message is 8kb.

我有一个类似的方法:

public void QueueMessage(string message)

在这个方法中,我想首先,压缩消息(大部分消息传递为JSON,所以都已经相当小)

Within this method, I'd like to first of all, compress the message (most messages are passed in as json, so are already fairly small)

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

If the compressed string is still larger than 8kb, I'll store it in S3.

我的问题是:

我怎样才能轻松地测试一个字符串的大小,什么是最好的方式压缩呢?
我不是在寻找大小,只是一些好和易于大量减少 - 易解压缩的另一端

How can I easily test the size of a string, and what's the best way to compress it? I'm not looking for massive reductions in size, just something nice and easy - and easy to decompress the other end.

推荐答案

要知道,我们需要知道的编码字符串的大小(以KB为单位)。如果我们假设UTF8,那么它是(不包括BOM等)如以下(但交换编码,如果它不是UTF8):

To know the "size" (in kb) of a string we need to know the encoding. If we assume UTF8, then it is (not including BOM etc) like below (but swap the encoding if it isn't UTF8):

int len = Encoding.UTF8.GetByteCount(longString);

重新包装它;我将通过UTF8建议GZIP,后面可以跟基64,如果它必须是一个字符串:

Re packing it; I would suggest GZIP via UTF8, optionally followed by base-64 if it has to be a string:

    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
    }

这篇关于如何确定串的大小,并压缩它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆