通过BinaryReader将字节数组解压缩为字符串,生成空字符串



我正在尝试解压缩字节数组,并使用二进制读取器将其转换为字符串。当执行下面的代码时,stream的位置从0变为数组的长度,但是str始终是一个空字符串。

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

您还没有展示如何压缩数据,但是这里有一个压缩和解压缩缓冲区的完整示例:

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

相关内容

  • 没有找到相关文章

最新更新