How to compress stream in memory

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I used use SharpZipLib to compress files in disk.

But now I want to compress stream into another stream in memory(the stream
not associated with disk file)

My pseudo is:

Stream InputStream;
Stream OutPutStream;
DataSet1.WriteXml(InputStream);
OutPutStream=ZipStream(InputStream);

How can I do that?
 
// Write compressed to network stream example - not compiled or tested.
using(NetworkStream ns = new NetworkStream(socket))
using ( GZipStream gz = new GZipStream(, CompressionMode.Compress, true) )
{
gz.Write(...); // Write bytes to compressed stream, which will
in-turn send the compressed bytes to the network stream.
// other work..
gz.Flush();
}

One issue with sending compressed streams over the network like this is you
don't know the stream size before hand so you can't prepend len bytes so the
other side know how many bytes to expect. So you either have to use some
kind of unique delimiter sequence (which could have some issues) or compress
the stream before hand and send that (which brings you back to same issue).
Small-to-Medium files could be compressed to a MemoryStream as long as RAM
is not an issue (but that is an unknown in most cases and probably not
something to count on).
 
If you are using .NET 2.0 or above, use the classes in the
System.IO.Compression namespace. You can use the GZipStream or the
DeflateStream class to wrap another stream, and write/read zipped contents
from it.

Hope this helps.
 
Thanks,
When compile this line
NetworkStream ns = new NetworkStream(socket);
It fail because socket not declare.
How can I new socket?
 
Thanks,
I have study GZipStream for a while , but I can not figure out how to do.
Please give me an example!


Nicholas Paldino said:
If you are using .NET 2.0 or above, use the classes in the
System.IO.Compression namespace. You can use the GZipStream or the
DeflateStream class to wrap another stream, and write/read zipped contents
from it.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

ad said:
I used use SharpZipLib to compress files in disk.

But now I want to compress stream into another stream in memory(the
stream not associated with disk file)

My pseudo is:

Stream InputStream;
Stream OutPutStream;
DataSet1.WriteXml(InputStream);
OutPutStream=ZipStream(InputStream);

How can I do that?
 
If you use a socket in your app, you can use that. It could be any Stream
however.
 
Back
Top