Add an Online Operator to Your Webs
  What Makes a Great Website Designer
  How to tell Which Kind of Website D
  Successful Web Design - How to Boos
  Static or Dynamic Websites: Does Yo
  Designing a Business Website
  HTML5 Mobile Development and Compil
  Website Design - I Want to Do My Ow
  How To Enhance The Usability Of You
  Concentrate Your Los Angeles SEO St


Compressing in Memory using MemoryStream
[Type:nina  Resource:information department  Publish date:2011/04/27]
  

Compressing in Memory using MemoryStream

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.

forward by www.okzyy.com