【问题标题】:Problem with decompress, GZipStream解压缩问题,GZipStream
【发布时间】:2011-05-15 12:54:43
【问题描述】:

我在解压 gzip 时遇到问题:

string fileData = string.Empty;
// byte[] starts with 31 and 139
var gzBuffer = entity.Data.Skip(pos).ToArray(); 
using (GZipStream stream = new GZipStream(new MemoryStream(gzBuffer),CompressionMode.Decompress))
{
    const int size = 4096;
    byte[] buffer = new byte[size];
    using (MemoryStream memory = new MemoryStream())
    {
        int count = 0;
        do
        {
            count = stream.Read(buffer, 0, size);
            if (count > 0)
            {
                memory.Write(buffer, 0, count);
            }
        } while (count > 0);
        fileData = Encoding.UTF8.GetString(memory.ToArray());
    }
}

在调试器中,count 总是等于 0。问题出在哪里?
谢谢。

【问题讨论】:

  • 这个流是如何压缩的?我过去也遇到过这个问题,错误实际上是在压缩逻辑中。
  • 你检查gzbuffer了吗?也许它是空的。
  • @Jan-Peter Vos:我不能肯定,因为消息来自网络。
  • @LightWing:是的,我检查过了。它包含数据
  • 嗯...我看不到任何明显的东西...“数据”是首先想到的。你能(例如)展示一下 gzBuffer 是什么吗?

标签: c# gzip memorystream gzipstream


【解决方案1】:

不确定这是否对您有很大帮助,但我会尝试。这是我在示例项目中使用 GZIP 压缩/解压缩文件的方法。也许您可以根据需要调整此代码?

public string Compress(FileInfo fi)
{
    string outPath;

    using (FileStream inFile = fi.OpenRead())
    {
        outPath = fi.FullName + ".gz";
        using (FileStream outFile = File.Create(outPath))
        {
            using (var compress = new GZipStream(outFile, 
                                                 CompressionMode.Compress))
            {
                inFile.CopyTo(compress);
            }
        }
    }

    return outPath;
}

public void Decompress(FileInfo fi)
{
    using (FileStream inFile = fi.OpenRead())
    {
        string curFile = fi.FullName;
        string origName = curFile.Remove(curFile.Length - fi.Extension.Length);

        using (FileStream outFile = File.Create(origName))
        {
            using (var decompress = new GZipStream(inFile, 
                                                   CompressionMode.Decompress))
            {
                decompress.CopyTo(outFile);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多