Reputation: 3462
Tyring to compress and decompress MemoryStream
but it seems that CopyTo
does not work like it's expected? Why? How to fix this?
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());
}
}
Output:
Original before compressing size: 5184054
Compressed size: 0
Compressed before decompressing size: 0
Decompressed size: 0
Upvotes: 5
Views: 1939
Reputation: 8871
CopyTo
starts copying bytes from the current position of the source stream.
Since you posted the resulting compressed stream size being 0, I'm pretty sure that originalStream
is positioned at the end of the stream, so no bytes were copied / compressed.
Ensure the position is 0
so it can find any data to copy and compress to your stream.
As @xanatos mentioned, the same applies to Decompress
, so ensure that compressedStream
is positioned at 0 too before decompressing it.
Upvotes: 6