How to determine size of string, and compress it

纵然是瞬间 提交于 2019-12-01 04:52:20

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);

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
    }

Give unzip bytes to this function.The best I could come up with was

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;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!