This project is read-only.

Zip to memory stream help

Jan 7, 2010 at 7:39 PM

Can anyone post some sample code that shows how to zip to a stream & save the stream to a table in a database?  Thanks...

Jan 7, 2010 at 7:46 PM
Edited Jan 7, 2010 at 7:49 PM

Saving to a MemoryStream is easy, right?  You just call zip.Save(memorystream), then you have the zipped content in the memorystream. 

using (var ms = new MemoryStream())
  using (var zip = new ZipFile())
  byte[] data = ms.ToArray();
  // upload this byte[] to the database.

Uploading to a database is also not too complicated.  Here's a nice article.

Instead of declaring a byte[] and filling it with data from the filesystem, as is done in that article, you just use MemoryStream.ToArray(), which returns a byte array of the zipped content.


using (SqlConnection Conn = new SqlConnection(ConnectionString))
        const string SQL = "INSERT INTO [BinaryTable] ([FileName], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (@FileName, @DateTimeUploaded, @MIME, @BinaryData)";
        SqlCommand cmd = new SqlCommand(SQL, Conn);
        cmd.Parameters.AddWithValue("@FileName", "");
        cmd.Parameters.AddWithValue("@MIME", fileType);
        cmd.Parameters.AddWithValue("@BinaryData", data);
        cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now);

Jan 7, 2010 at 9:01 PM

Thanks, I will give it a try...

Mar 3, 2010 at 7:48 AM

Is it possible to use this method but instead of uploading to a SQL-server, upload to a Webserver with WebClient.DataUpload()?

I tried to do it yeasterday, but my script on the webserver can't find any files in the POST request, it works great when doing a and WebClient.UploadFile(), but it would be better to upload the memorystream directly.



Mar 3, 2010 at 6:39 PM

Yes, you will be able to upload a MemoryStream with WebClient.UploadData().  A common problem is that people don't remember to reset the cursor in the MemoryStream, after writing and before reading.  If you don't reset the cursor (via MemoryStream.Position = 0, or MemoryStream.Seek(0, SeekOrigin.Begin)) then the call to UploadData will get no data.  This has nothing to do with zip files.   It's just how the MemoryStream works.