要压缩和解压缩MemoryStream
的轮胎,但是看来CopyTo
不能像预期的那样工作?为什么?该如何解决?
public static MemoryStream Compress(MemoryStream originalStream)
{
Console.WriteLine("Original before compressing size: {0}", originalStream.Length.ToString());
MemoryStream compressedMemoryStream = new MemoryStream();
using (DeflateStream deflateStream = new DeflateStream(compressedMemoryStream, CompressionMode.Compress, true))
{
originalStream.CopyTo(deflateStream);
}
Console.WriteLine("Compressed size: {0}", compressedMemoryStream.Length.ToString());
return compressedMemoryStream;
}
public static void Decompress(MemoryStream compressedStream)
{
Console.WriteLine("Compressed before decompressing size: {0}", compressedStream.Length.ToString());
using (MemoryStream decompressedFileStream = new MemoryStream())
{
using (DeflateStream decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
{
decompressionStream.CopyTo(decompressedFileStream);
}
Console.WriteLine("Decompressed size: {0}", decompressedFileStream.Length.ToString());
}
}
输出:
Original before compressing size: 5184054
Compressed size: 0
Compressed before decompressing size: 0
Decompressed size: 0
答案 0 :(得分:3)
CopyTo
开始从源流的当前位置复制字节。
由于您发布的压缩流大小为0,所以我很确定originalStream
位于流的末尾,因此没有字节被复制/压缩。
确保位置为0
,以便它可以找到要复制并压缩到流中的任何数据。
如@xanatos所述,Decompress
同样适用,因此在解压缩之前,请确保compressedStream
也位于0。