.NET GZipStream解压MIME中compressed-data报错,求解决方案
我需要解压MIME消息中标记为compressed-data的数据,编写了如下.NET代码:
using (var msi = new MemoryStream(content)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) gs.CopyTo(mso); var a = mso.ToArray(); }
执行时抛出异常:
Found invalid data while encoding
at System.IO.Compression.InflaterZlib.Inflate(FlushCode flushCode)
at System.IO.Compression.InflaterZlib.ReadInflateOutput(Byte[] outputBuffer, Int32 offset, Int32 length, FlushCode flushCode, Int32& bytesRead)
at System.IO.Compression.InflaterZlib.Inflate(Byte[] bytes, Int32 offset, Int32 length)
at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.IO.Compression.GZipStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.IO.Stream.InternalCopyTo(Stream destination, Int32 bufferSize)
at System.IO.Stream.CopyTo(Stream destination)
根据RFC规范,该数据应为标准GZIP格式。查看MimeKit代码后发现,其底层使用BouncyCastle的CmsCompressedDataParser可成功解压相同数据:
var cdata = File.ReadAllBytes("C://test//as2//CompressedContentPartContent.bin"); CmsCompressedDataParser ed = new CmsCompressedDataParser(cdata); var aa = CmsTestUtil.StreamToByteArray(ed.GetContent().ContentStream);
但公司政策要求避免使用第三方库,因此困惑为何.NET标准库的GZipStream和DeflateStream均报错,而CmsCompressedDataParser可正常工作?另外尝试SharpZipLib也失败,错误信息如下:
Error GZIP header, first magic byte doesn't match
at ICSharpCode.SharpZipLib.GZip.GZipInputStream.ReadHeader()
at ICSharpCode.SharpZipLib.GZip.GZipInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(Stream source, Stream destination, Byte[] buffer)
at ICSharpCode.SharpZipLib.GZip.GZip.Decompress(Stream inStream, Stream outStream, Boolean isStreamOwner)
我对比了两份数据的头部字节,结果匹配,求问问题原因。
内容的提问来源于stack exchange,提问作者katit

