You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET GZipStream解压MIME中compressed-data报错,求解决方案

.NET标准库GZipStream无法解压MIME的compressed-data数据,而BouncyCastle可以

我需要解压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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:42:46