Geeks With Blogs

Lance's TextBox

Recently, several people have asked me the same question:  How do I zip from a memory stream to a memory stream?

With the Zip component that comes in IPWorks Zip, you can zip from any kind of file or stream to any kind of stream or file.  There is one trick to going from memory stream to memory stream though - and that is keeping the stream open after compressing.

By default, the component will automatically close an input stream after it compresses from it.  But we added a config setting that you can use to turn this off and manually close the stream yourself after you're really done with it (after the extraction or whatever other plans you have for the stream after compression).

The compression:

   1:  MemoryStream file1 = new MemoryStream(GetBytes("This is test 1"));
   2:  MemoryStream file2 = new MemoryStream(GetBytes("This is test 2"));
   3:  MemoryStream myStream = new MemoryStream();
   5:  Zip zip = new Zip();
   6:  zip.SetArchiveOutputStream(myStream);
   7:  zip.Files.Add(new ZIPFile("test.txt", file1InputStream));
   8:  zip.Files.Add(new ZIPFile("test2.txt", file2InputStream));
   9:  //config the component to keep the stream open
  10:  zip.Config("CloseStreamAfterCompress=false");
  11:  zip.Compress();

Now I can get onto whatever business I have with the compressed stream.  If I want to extract an already compressed stream, its just as easy:

   1:  //make sure I'm at the beginning of the compressed data:
   2:  myStream.Seek(0, SeekOrigin.Begin);
   4:  zip = new Zip();
   5:  zip.ExtractToPath = "..\\myextractedfiles\\";
   6:  zip.SetArchiveInputStream(myStream);
   7:  zip.ExtractAll();
   8:  myStream.Close();

Hope this helps!

Technorati Tags: ,
Posted on Thursday, May 22, 2008 4:04 PM Programming | Back to top

Comments on this post: Zipping data from/to memory

# re: Zipping data from/to memory
Requesting Gravatar...
I tell you, I usually get irked when folks discuss issues that they plainly do not know about.
Left by kinky toys on Oct 08, 2012 6:28 PM

Your comment:
 (will show your gravatar)

Copyright © Lance Robinson | Powered by: