Quantcast
Channel: C# Help » compression
Viewing all articles
Browse latest Browse all 4

Compressing in Memory using MemoryStream

$
0
0

Sometimes you need to compress entirely in memory. Here’s how to use a MemoryStream for this purpose:

byte[] data = new byte[1000]; // We would expect a good compression ratio from an empty array!
var msObj = new MemoryStream();
using (Stream ds = new DeflateStream (msObj, CompressionMode.Compress))
ds.Write (data, 0, data.Length);
byte[] compressed = msObj.ToArray();
Console.WriteLine (compressed.Length); // 113
// Decompress back to the data array:
msObj= new MemoryStream (compressed);
using (Stream ds = new DeflateStream (msObj, CompressionMode.Decompress))
for (int i = 0; i < 1000; i += ds.Read (data, i, 1000 - i));

In the above code the using statement wrapped around the DeflateStream closes it in  textbook fashion, and flushes  unwritten buffers in the process. The structure also closes the MemoryStream it wraps and so we will  then need to call ToArray to extract its data.
The below code shows an alternative which avoids closing the MemoryStream:

byte[] data = new byte[1000];
MemoryStream  msObj= new MemoryStream();
using (Stream ds = new DeflateStream (ms, CompressionMode.Compress, true))
ds.Write (data, 0, data.Length);
Console.WriteLine (msObj.Length); // 113
msObj.Position = 0;
using (Stream ds = new DeflateStream (msObj, CompressionMode.Decompress))
for (int i = 0; i < 1000; i += ds.Read (data, i, 1000 - i));

Here, the additional flag which is sent to the DeflateStream’s constructor instructs it not to follow the usual protocol of taking the underlying stream with it in disposal. Thus, the MemoryStream is still left open, allowing us to reposition it  to zero and then reread it.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images