C# GZipStream 在通过 MemoryStream 解压时不能使用 CopyTo 方法

C# GZipStream cannot use the CopyTo method when decompressed via MemoryStream

// code href="https://www.cnblogs.com/mahuanpeng/p/6851793.html" 
// Compress bytes
//1. Create a compressed data stream
//2. Set compressStream to store the compressed file stream and set it to compression mode
//3. Write the bytes to be compressed to the compressed file stream
public static byte[] CompressBytes(byte[] bytes)
{
  Using (MemoryStream by compressStream = new MemoryStream())
  {
     Using (var zipStream = new GZipStream(compressStream, System.IO.Compression.CompressionLevel.SmallestSize))
     ZipStream.Write(bytes,0, bytes.Length).
     Return compressStream.ToArray();
  }
}


// Unzip the bytes
//1. Create a compressed data stream
//2. Create the GzipStream object and pass in the unzipped file stream
//3. Create the target flow
//4. Copy zipStream to the destination stream
//5. Return destination stream output bytes
public static byte[] Decompress(byte[] bytes)
{
  Using (var compressStream = new MemoryStream(bytes))
  {
    Using (var zipStream = new GZipStream(compressStream, System.IO.Compression.CompressionLevel.SmallestSize)
    {
      Using (var resultStream = new MemoryStream())
      {
        ZipStream.CopyTo(resultStream);
        Return resultStream.ToArray();
      }
    }
  }
}

这似乎是正确的,但在“解压缩代码”中,出现以下异常:

Unhandled exception. System.NotSupportedException: Specified method is not supported.
 At System.IO.Compression.DeflateStream.CopyTo(Stream destination, Int32 bufferSize)
 At System.IO.Compression.GZipStream.CopyTo(Stream destination, Int32 bufferSize)
 At System.IO.Stream.CopyTo(Stream destination)
 Version: .NET6

我不得不压缩和解压缩内存中的数据。我没有使用 FileStream 和临时文件,而是使用了。 NET6​​,压缩功能没规定,只要能用就行。 NET 库而不是 nuget 包。如果 Nuget 上有更好的选择,我会考虑的。其他替代方案也是可以接受的,只要达到 byte[] 压缩和解压缩的性能即可。此程序需要跨平台!

您创建了一个压缩流,您需要一个解压流:

using var unzipStream = new GZipStream(compressStream, CompressionMode.Decompress);