Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.
It would be nice to be able to do this using SharpZipLib.
I come across this problem, using the MSDN example I created this class:
You can then use it like this:
You can pass a
MemoryStream
(or anyStream
) toZipSticle.Add
such as:Yes, you can use SharpZipLib to do this - when you need to supply a stream to write to, use a
MemoryStream
.I was utilizing Cheeso's answer by adding
MemoryStream
s as the source of the different Excel files. When I downloaded the zip, the files had nothing in them. This could be the way we were getting around trying to create and download a file over AJAX.To get the contents of the different Excel files to be included in the Zip, I had to add each of the files as a
byte[]
.This function should create a byte array from a stream of data: I've created a simple interface for handling files for simplicity
Use
ZipEntry
andPutNextEntry()
for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStreamUsing SharpZipLib for this seems pretty complicated. This is so much easier in DotNetZip. In v1.9, the code looks like this:
The code above assumes stringContent{1,2,3} contains the data to be stored in the files (or entries) in the zip archive. The first entry is "Readme.txt" and it is stored in the top level "Directory" in the zip archive. The next two entries are stored in the "readings" directory in the zip archive.
The strings are encoded in the default encoding. There is an overload of AddEntry(), not shown here, that allows you to explicitly specify the encoding to use.
If you have the content in a stream or byte array, not a string, there are overloads for AddEntry() that accept those types. There are also overloads that accept a Write delegate, a method of yours that is invoked to write data into the zip. This works for easily saving a DataSet into a zip file, for example.
DotNetZip is free and open source.