Zipping data from/to memory

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();
   4:   
   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);
   3:   
   4:  zip = new Zip();
   5:  zip.ExtractToPath = "..\\myextractedfiles\\";
   6:  zip.SetArchiveInputStream(myStream);
   7:  zip.ExtractAll();
   8:  myStream.Close();

Hope this helps!

Technorati Tags: ,

Print | posted on Thursday, May 22, 2008 4:04 PM

Feedback

No comments posted yet.

Your comment:





 
 

Copyright © Lance Robinson

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski