How to compress stream in memory

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?
 
W

William Stacey [MVP]

// 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).
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
A

ad

Thanks,
When compile this line
NetworkStream ns = new NetworkStream(socket);
It fail because socket not declare.
How can I new socket?
 
A

ad

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?
 
W

William Stacey [MVP]

If you use a socket in your app, you can use that. It could be any Stream
however.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top