Decompress byte array to string via BinaryReader yields empty string

一笑奈何 提交于 2019-12-04 21:22:19

问题


I am trying to decompress a byte array and get it into a string using a binary reader. When the following code executes, the inStream position changes from 0 to the length of the array, but str is always an empty string.

BinaryReader br = null;
string str = String.Empty;

using (MemoryStream inStream = new MemoryStream(pByteArray))
{
    GZipStream zipStream = new GZipStream(inStream, CompressionMode.Decompress);
    BinaryReader br = new BinaryReader(zipStream);
    str = br.ReadString();
    inStream.Close();
    br.Close();
}

回答1:


You haven't shown how is the data being compressed, but here's a full example of compressing and decompressing a buffer:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

class Program
{
    static void Main()
    {
        var test = "foo bar baz";

        var compressed = Compress(Encoding.UTF8.GetBytes(test));
        var decompressed = Decompress(compressed);
        Console.WriteLine(Encoding.UTF8.GetString(decompressed));
    }

    static byte[] Compress(byte[] data)
    {
        using (var compressedStream = new MemoryStream())
        using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
        {
            zipStream.Write(data, 0, data.Length);
            zipStream.Close();
            return compressedStream.ToArray();
        }
    }

    static byte[] Decompress(byte[] data)
    {
        using (var compressedStream = new MemoryStream(data))
        using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
        using (var resultStream = new MemoryStream())
        {
            zipStream.CopyTo(resultStream);
            return resultStream.ToArray();
        }
    }
}


来源:https://stackoverflow.com/questions/7013771/decompress-byte-array-to-string-via-binaryreader-yields-empty-string

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