// 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
Although I tried this: C# Unable to copy to MemoryStream from GZipStream
我不得不压缩和解压缩内存中的数据。我没有使用FileStream和临时文件,而是使用了。NET6,只要可以使用,压缩函数就不会被指定。NET库,而不是nuget包。如果在Nuget有更好的选择,我会考虑的。只要实现了byte[]压缩和解压缩的性能,其他替代方案也是可以接受的。这个程序需要跨平台!
发布于 2022-01-28 03:16:59
如果创建了压缩流,则需要解压缩流:
using var unzipStream = new GZipStream(compressStream, CompressionMode.Decompress);
https://stackoverflow.com/questions/70888398
复制相似问题