gpt4 book ai didi

c# - 通过 BinaryReader 将字节数组解压缩为字符串会产生空字符串

转载 作者:太空狗 更新时间:2023-10-29 20:51:59 26 4
gpt4 key购买 nike

我正在尝试解压缩字节数组并使用二进制读取器将其转换为字符串。执行以下代码时,inStream位置从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();
}
}
}

关于c# - 通过 BinaryReader 将字节数组解压缩为字符串会产生空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7013771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com