Gzip魔术数字解压缩时出现问题

时间:2018-11-26 13:48:18

标签: c# asp.net xml gzip

我从Web服务获取字符串结果,并使用以下代码对其进行解析:

 public static T FromXmlString<T>(string xml)
    {
        T xmlClass = default(T);


            using (TextReader reader = new StringReader(xml))
            {
                try
                {
                    xmlClass =
                        (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                }
                catch (InvalidOperationException e)
                {
                    //
                }
            }


        return xmlClass;
    }

结果是压缩的字符串,解析后我尝试将其解压缩 使用以下代码

  byte[] bytes = Convert.FromBase64String(voucher.Document.Value);
              using (var compressedStream = new MemoryStream(bytes))
  using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
  using (var resultStream = new MemoryStream())
        {
            zipStream.CopyTo(resultStream);
            return File(resultStream.ToArray(), "application/pdf", "voucher.pdf");
        }

但是我每次都失败。它引发以下错误: “ GZip标头中的魔术数字不正确。请确保您正在传递GZip流。”

我知道有很多与此类似的问题。我尝试了以下链接中的所有答案:

Compression/Decompression string with C#

Error decompressing gzipstream -- The magic number in GZip header is not correct

https://social.msdn.microsoft.com/Forums/vstudio/en-US/21901efe-8d36-40ed-9dad-2ce9968b4273/the-magic-number-in-gzip-header-is-not-correct-error?forum=csharpgeneral

但是没有得到任何结果。伙计们,您知道为什么我会收到此错误吗?我的代码有什么问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。经过研究后,我发现了这一点:

Why does my C# gzip produce a larger file than Fiddler or PHP?

然后我使用了Ionic.Zlib libray。使用它,我可以解压缩并获取原始文件,而没有任何问题。

这是我的代码段:

     byte[] bytes = Convert.FromBase64String(voucher.Document.Value);
     var zippedStream = new MemoryStream(bytes);
     var decompressed = new MemoryStream();
     zOut = new ZlibStream(decompressed, Ionic.Zlib.CompressionMode.Decompress, 
true);
      CopyStream(zippedStream, zOut);
      byte[] byteArray = decompressed.ToArray();
      return File(byteArray, "application/pdf", "voucher.pdf");

CopyStream函数:

 static void CopyStream(System.IO.Stream src, System.IO.Stream dest)
    {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = src.Read(buffer, 0, buffer.Length)) > 0)
            dest.Write(buffer, 0, len);
        dest.Flush();
    }