首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C# GZipStream在通过MemoryStream解压缩时不能使用CopyTo方法

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

Stack Overflow用户
提问于 2022-01-28 03:09:53
回答 1查看 614关注 0票数 0
代码语言:javascript
运行
复制
// 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();
      }
    }
  }
}

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

代码语言:javascript
运行
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-28 03:16:59

如果创建了压缩流,则需要解压缩流:

代码语言:javascript
运行
复制
using var unzipStream = new GZipStream(compressStream, CompressionMode.Decompress);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70888398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档