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

标签 c# .net c#-4.0 c#-3.0 gzip

我构建了(基于 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/

相关文章:

c# - 在运行时使用 jQuery 将 JavaScript 注入(inject) WebBrowser

c# - .NET 空闲内存使用(如何防止过度分配/释放内存给操作系统)

c# - .Net存在: chicken and eggs?

.net - .Net 是否有任何 Common Lisp 实现?

c# - 如何在 DataGridView 中制作 ComboBox 列?

c# - C# 中的 setjmp/longjmp。是否可以?

c# - 在 MVC 3 的多个位置搜索 .cshtml?

c# - 林克 : query with three nested levels

c#-4.0 - Parallel.Invoke - 异常处理

c# - EnumerateFiles 中的配置 SearchPattern