簡體   English   中英

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

雖然我試過這個:C# Unable to copy to MemoryStream from GZipStream

我不得不壓縮和解壓縮 memory 中的數據。 我沒有使用 FileStream 和臨時文件,而是使用了。 NET6,壓縮function不指定,只要能用就行。 NET 庫,而不是 nuget package。 如果 Nuget 有更好的選擇,我會考慮。 其他替代方案也是可以接受的,只要達到 byte[] 壓縮和解壓的性能即可。 這個程序需要跨平台!

你創建了一個壓縮stream,你需要一個解壓stream來代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM