3

我是System.IO.Compression的新手

我正在尝试压缩和解压缩一些信息。

对于压缩,我使用了代码项目,它似乎可以工作。我现在正在压缩字符串。

为了解压,我想压缩一个Stream

这就是我目前所拥有的

        var zipString = _compressor.Compress(request);
        using (var sw = new StreamWriter(req.GetRequestStream()))
        {
            sw.Write(zipString);
            sw.Close();
        }

        WebResponse respStream = req.GetResponse();
        Stream resp = respStream.GetResponseStream();                      
        resp = _compressor.UnCompress(resp);

这是压缩的代码

    public string Compress(string s)
    {
        //Transforming string into byte
        var byteArray = new byte[s.Length];
        var indexBa = 0;
        foreach (var item in s.ToCharArray())
        {
            byteArray[indexBa++] = (byte) item;
        }

        //prepare for compress
        var ms = new MemoryStream();
        var sw = new GZipStream(ms, CompressionMode.Compress);

        //compress
        sw.Write(byteArray,0,byteArray.Length);

        //close sw, DO NOT FLUSH because byes will go missing...
        sw.Close();

        //transform byte[] zip data to string
        byteArray = ms.ToArray();
        var sb = new StringBuilder(byteArray.Length);
        foreach (var item in byteArray)
        {
            sb.Append((char) item);
        }
        ms.Close();
        sw.Dispose();
        ms.Dispose();
        return sb.ToString();
    }

这是解压缩的代码

    public Stream UnCompress(Stream s)
    {
        int readCount;
        MemoryStream mem = new MemoryStream();
        byte[] tmp = new byte[128];
        while ((readCount = s.Read(tmp, 0, 128)) != 0)
        {
            mem.Write(tmp, 0, readCount);
        }
        StreamReader reader = new StreamReader(mem);
        char[] buffer = new char[mem.Length];
        mem.Position = 0;
        reader.ReadBlock(buffer, 0, (int)mem.Length);

        byte[] zip = Encoding.UTF8.GetBytes(buffer, 0, (int)mem.Length);
        Stream wr = new MemoryStream();
        wr.Write(zip, 0, zip.Length);
        wr.Position = 0;
        using (var stream = new GZipStream(wr, CompressionMode.Decompress))
        {                
            mem = new MemoryStream();
            while ((readCount = stream.Read(tmp, 0, 128)) != 0)
            {
                mem.Write(tmp, 0, readCount);
            }
            mem.Position = 0;
            return mem;
        }        
    }

此时我在以下行中解压缩时出错:

while ((readCount = stream.Read(tmp, 0, 128)) != 0)
{
     mem.Write(tmp, 0, readCount);
}

它只是不进入while循环并说:

GZip 标头中的幻数不正确。确保您传入的是 GZip 流

我的解压方法基于以下stackoverflow帖子

尝试2:

        public Stream UnCompress(Stream s)
        {
            byte[] byteArray = null;
            using (var m = new MemoryStream())
            {
                int count;
                do
                {
                    byte[] buf = new byte[1024];
                    count = s.Read(buf, 0, 1024);
                    m.Write(buf, 0, count);
                } while (s.CanRead && count > 0);
                byteArray = m.ToArray();
            }
            var indexBa = 0;
            foreach (var item in s.ToString().ToCharArray())
            {
                byteArray[indexBa++] = (byte) item;
            }
            //Prepare for decompress
            var ms = new MemoryStream(byteArray);
            var sr = new GZipStream(ms,
                CompressionMode.Decompress);

            //Reset variable to collect uncompressed result
            byteArray = new byte[byteArray.Length];

            //Decompress
            var rByte = sr.Read(byteArray, 0, byteArray.Length);

            //Transform byte[] unzip data to string
            var sB = new MemoryStream(rByte);

            for (var i = 0; i < rByte; i++)
            {
                sB.Write(byteArray,0,rByte);
            }
            sr.Close();
            ms.Close();
            sr.Dispose();
            ms.Dispose();
            return sB;
        }

结果: var rByte = sr.Read(byteArray, 0, byteArray.Length); 更新 1 行中的相同错误:

正如代码项目中给出的解压缩字符串完美地工作。

public static string UnZip(string value)
{
    //Transform string into byte[]
    byte[] byteArray = new byte[value.Length];
    int indexBA = 0;
    foreach (char item in value.ToCharArray())
    {
        byteArray[indexBA++] = (byte)item;
    }

    //Prepare for decompress
    System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
    System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
        System.IO.Compression.CompressionMode.Decompress);

    //Reset variable to collect uncompressed result
    byteArray = new byte[byteArray.Length];

    //Decompress
    int rByte = sr.Read(byteArray, 0, byteArray.Length);

    //Transform byte[] unzip data to string
    System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
    //Read the number of bytes GZipStream red and do not a for each bytes in
    //resultByteArray;
    for (int i = 0; i < rByte; i++)
    {
        sB.Append((char)byteArray[i]);
    }
    sr.Close();
    ms.Close();
    sr.Dispose();
    ms.Dispose();
    return sB.ToString();
}
4

1 回答 1

5

您的代码有很多问题,因此从头开始编写另一个版本会更容易。请注意,这样做:

var byteArray = new byte[s.Length];
var indexBa = 0;
foreach (var item in s.ToCharArray())
{
    byteArray[indexBa++] = (byte) item;
}

将字符串转换为字节数组不是一个好主意。而是选择一些编码并使用它进行转换。此外,将压缩结果作为字符串返回也不是一个好主意 - 而是返回一个字节数组,因为该字节数组并不真正代表任何字符串 - 它只是任意二进制数据。

示例代码:

static byte[] Compress(byte[] data) {
    // `compressed` will contain result of compression
    using (var compressed = new MemoryStream()) {
        // source is our original uncompressed data
        using (var source = new MemoryStream(data)) {
            using (var gzip = new GZipStream(compressed, CompressionMode.Compress)) {
                // just write whole source into gzip stream with CopyTo
                source.CopyTo(gzip);
            }
        }
        return compressed.ToArray();
    }
}

static byte[] CompressString(string s, Encoding encoding) {
    return Compress(encoding.GetBytes(s));
}

static string CompressStringToBase64(string s, Encoding encoding) {
    return Convert.ToBase64String(CompressString(s, encoding));
}

static byte[] Decompress(Stream source) {
    using (var gzip = new GZipStream(source, CompressionMode.Decompress)) {
        using (var decompressed = new MemoryStream()) {
            gzip.CopyTo(decompressed);
            return decompressed.ToArray();
        }
    }
}

static byte[] Decompress(byte[] data) {
    using (var ms = new MemoryStream(data)) {
        return Decompress(ms);
    }
}

static string DecompressString(Stream source, Encoding encoding) {
    return encoding.GetString(Decompress(source));
}

测试

var source = "Some string";
var compressed = CompressString(source, Encoding.UTF8);            
var decompressed = DecompressString(new MemoryStream(compressed), Encoding.UTF8);
Debug.Assert(source == decompressed);
于 2017-11-27T15:27:36.177 回答