Search code examples
c#memorystream.net-6.0gzipstreamnotsupportedexception

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

This may seem correct, but in "unzipped code", the following exception occurs:

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

Although I tried this: C# Unable to copy to MemoryStream from GZipStream

I had to compress and decompress the data in memory. Instead of using FileStream and temporary files, I used. NET6, the compression function is not specified, as long as it can be used. NET library instead of nuget package. If there is a better alternative on Nuget, I would consider it. Other alternatives are also acceptable, as long as the performance of byte[] compression and decompression is achieved. This program needs to be cross-platform!


Solution

  • You created a compression stream, you need a decompression stream instead:

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