gpt4 book ai didi

c# - 使用 GZipStream 对 MemoryStream 进行编程压缩/解压缩

转载 作者:太空狗 更新时间:2023-10-30 00:34:52 28 4
gpt4 key购买 nike

我构建了(基于 CodeProject 文章)包装类 (C#) 以使用 GZipStream 来压缩 MemoryStream 。它可以很好地压缩但不会解压。我看了很多其他有同样问题的例子,我觉得我在按照所说的进行操作,但在解压缩时仍然一无所获。下面是压缩和解压方法:

public static byte[] Compress(byte[] bSource)
{

using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
{
gzip.Write(bSource, 0, bSource.Length);
gzip.Close();
}

return ms.ToArray();
}
}


public static byte[] Decompress(byte[] bSource)
{

try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true))
{
gzip.Read(bSource, 0, bSource.Length);
gzip.Close();
}

return ms.ToArray();
}
}
catch (Exception ex)
{
throw new Exception("Error decompressing byte array", ex);
}
}

这是我如何使用它的示例:

string sCompressed = Convert.ToBase64String(CompressionHelper.Compress("Some Text"));
// Other Processes
byte[] bReturned = CompressionHelper.Decompress(Convert.FromBase64String(sCompressed));
// bReturned has no elements after this line is executed

最佳答案

解压方法有问题

代码不读取bSource 的内容。相反,它会覆盖其从基于空内存流创建的空 gzip 读取的内容。

基本上您的代码版本在做什么:

//create empty memory
using (MemoryStream ms = new MemoryStream())

//create gzip stream over empty memory stream
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))

// write from empty stream to bSource
gzip.Write(bSource, 0, bSource.Length);

修复可能如下所示:

public static byte[] Decompress(byte[] bSource)
{
using (var inStream = new MemoryStream(bSource))
using (var gzip = new GZipStream(inStream, CompressionMode.Decompress))
using (var outStream = new MemoryStream())
{
gzip.CopyTo(outStream);
return outStream.ToArray();
}
}

关于c# - 使用 GZipStream 对 MemoryStream 进行编程压缩/解压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350776/

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