解压时出现Gzip幻数问题

Gzip magic number problem while decompressing it

我正在从 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");
        }

但我每次都失败了。它抛出以下错误: "The magic number in GZip header is not correct. Make sure you are passing in a GZip stream."

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

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

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

提前致谢!

我发现了问题。经过更多研究,我发现了这个:

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

并且我使用了 Ionic.Zlib 库。通过使用它,我可以毫无问题地解压缩并获取原始文件。

这是我的代码片段:

     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");

复制流函数:

 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();
    }