ZIP archives in memory
A ZIP archive does not have to be a file. ZipArchive works on any stream, so a MemoryStream can hold a whole archive in memory — useful for a download that a web program sends, or for a test that leaves no files behind. This lesson creates, reads, compresses and updates an archive.
What you will learn#
ZipArchiveon aMemoryStream(modesCreate,Read,Update),CreateEntry,Entries,GetEntry,Delete,- why
Disposeis needed, - compression levels,
- checking the names of entries.
The tutorial Files and folders made a ZIP file from a folder, the tutorial Compression compressed streams and the tutorial Tar archives made tar archives. This lesson works with the entries of an archive one by one.
The program#
# ZIP archives in memory - ZipArchive on a MemoryStream, entries, reading one file, compression levels, and updating an archive
load "dotnet.ring"
using {
"System"
"System.IO"
"System.IO.Compression"
"System.Text"
}
func main
oUtf8 = new UTF8Encoding()
# 1. A ZIP archive does not have to be a file. ZipArchive works on any stream: a MemoryStream keeps the whole archive in memory, which is
# what a web program does when it sends a download, or a test that does not want to leave files on the disk.
oMemory = new MemoryStream
oZip = (new ZipArchive).@New([ :stream = oMemory, :mode = "Create", :leaveOpen = True ])
addEntry(oZip,"readme.txt","Read me first." + nl + "Second line.")
addEntry(oZip,"data/numbers.txt",copy("1234567890 ",500))
addEntry(oZip,"data/names.txt","Ann" + nl + "Bob" + nl + "Cy")
oZip.Dispose() # Dispose writes the end of the archive: without it the archive is incomplete
? "1. an archive with 3 files is in memory, it has bytes: " + (oMemory.Length > 0)
# 2. Read it: open the archive again for reading and list the entries (full name, size, compressed size)
oMemory.Position = 0
oRead = (new ZipArchive).@New([ :stream = oMemory, :mode = "Read", :leaveOpen = True ])
? nl + "2. the entries:"
aEntries = oRead.Entries.toList()
for oEntry in aEntries
? " " + padRight(oEntry.FullName,18) + padLeft("" + oEntry.Length,6) + " bytes, packed smaller than the original: " + (oEntry.CompressedLength < oEntry.Length)
next
# 3. Read one file: GetEntry finds it by name (null when it is not there), Open gives a stream to read it
oEntry = oRead.GetEntry("data/names.txt")
oReader = new StreamReader(oEntry.Open())
? nl + "3. data/names.txt contains: " + substr(substr(oReader.ReadToEnd(),char(13),""),nl,", ")
oReader.Dispose()
oMissing = oRead.GetEntry("nothing.txt")
? " GetEntry of a missing name is null: " + oMissing.isNull()
oRead.Dispose()
# 4. The same text with different compression levels. The size of the archive is the size of the MemoryStream after the archive was
# closed. The exact numbers depend on the version of the compression library, so the program compares them.
cLong = copy("1234567890 ",500)
nNone = packSize("NoCompression",cLong)
nFast = packSize("Fastest",cLong)
nBest = packSize("SmallestSize",cLong)
? nl + "4. the same 5500 characters in an archive:"
? " without compression the archive is bigger than the text: " + (nNone > len(cLong))
? " fastest is much smaller than no compression: " + (nFast < nNone / 10)
? " smallest size is not bigger than fastest: " + (nBest <= nFast)
# 5. Update: open the archive in Update mode, add a file and delete another one
oMemory.Position = 0
oUpdate = (new ZipArchive).@New([ :stream = oMemory, :mode = "Update", :leaveOpen = True ])
addEntry(oUpdate,"notes/new.txt","added later")
oUpdate.GetEntry("data/numbers.txt").Delete()
oUpdate.Dispose()
oMemory.Position = 0
oCheck = (new ZipArchive).@New([ :stream = oMemory, :mode = "Read" ])
cNames = ""
aItems = oCheck.Entries.toList()
for oItem in aItems
cNames += oItem.FullName + " "
next
? nl + "5. after the update: " + cNames
oCheck.Dispose()
# 6. Names inside an archive use / and must stay inside: an entry called ../../x would be written outside the target folder when
# somebody unpacks it (the tutorial "Tar archives" warns about it). Check each name before you unpack by hand.
? nl + "6. a safe name has no '..' part and does not start with '/': " + safeName("data/names.txt") + ", " + safeName("../../etc/passwd") + ", " + safeName("/absolute.txt")
func addEntry oZip,cName,cText
oEntry = oZip.CreateEntry(cName)
oWriter = new StreamWriter(oEntry.Open())
oWriter.Write(cText)
oWriter.Dispose()
func packSize cLevel,cText
oStream = new MemoryStream
oZip = (new ZipArchive).@New([ :stream = oStream, :mode = "Create", :leaveOpen = True ])
oEntry = oZip.CreateEntry([ :entryName = "text.txt", :compressionLevel = cLevel ])
oWriter = new StreamWriter(oEntry.Open())
oWriter.Write(cText)
oWriter.Dispose()
oZip.Dispose() # the size is known when the archive is closed
return oStream.Length
func safeName cName
if left(cName,1) = "/" or left(cName,1) = "\" or substr(cName,"..") > 0
return "unsafe"
ok
return "safe"
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))
func padLeft cText,nWidth
return copy(" ",nWidth - len(cText)) + cText1. an archive with 3 files is in memory, it has bytes: 1
2. the entries:
readme.txt 27 bytes, packed smaller than the original: 0
data/numbers.txt 5500 bytes, packed smaller than the original: 1
data/names.txt 10 bytes, packed smaller than the original: 0
3. data/names.txt contains: Ann, Bob, Cy
GetEntry of a missing name is null: 1
4. the same 5500 characters in an archive:
without compression the archive is bigger than the text: 1
fastest is much smaller than no compression: 1
smallest size is not bigger than fastest: 1
5. after the update: readme.txt data/names.txt notes/new.txt
6. a safe name has no '..' part and does not start with '/': safe, unsafe, unsafeThis program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
The stream#
ZipArchive is made on a stream and a mode: dnNew("ZipArchive",[ :stream = oMemory, :mode = "Create", :leaveOpen = True ]). leaveOpen = True keeps the MemoryStream open when the archive is closed, so the program can read the bytes afterwards (ToArray()), send them or open the archive again. Without it, closing the archive also closes the stream. The mode is an enum, so it is a text.
Creating entries#
CreateEntry("data/names.txt") makes an entry (a file inside the archive; folders are just a / in the name) and Open() gives a stream to write its content, here a StreamWriter. Dispose() of the archive is required: it writes the central directory at the end of the archive. A ZIP file or stream that was not disposed is incomplete and other programs cannot read it.
Reading#
Open the stream again (Position = 0) in Read mode. Entries lists every entry with FullName, Length (the original size) and CompressedLength. GetEntry(name) finds one by name and gives a null object when it is missing (isNull()); Open() returns a stream with the content. A very small file may become bigger in the archive (the names.txt of 10 bytes), because every entry has a header; compression helps when there is something to compress, like the repeated text of 5500 characters.
Compression levels#
CompressionLevel (NoCompression, Fastest, Optimal, SmallestSize) is a second value of CreateEntry. NoCompression stores the data as it is, Fastest gives a good result quickly and SmallestSize takes more time for a smaller result. The size of an entry can be read after the archive is closed (CompressedLength raises "Length properties are unavailable once an entry has been opened for writing" before that), so the program measures the length of the MemoryStream. The exact numbers depend on the version of the compression library, which is why the output only compares them.
Updating#
Update mode opens an existing archive for changes: add entries, Delete() others. Everything is written when the archive is disposed. For a big archive, Update copies data around; if you only append, it is cheaper to read the old archive and write a new one.
Names#
An entry name is just text, and a bad archive can contain ../../etc/passwd. A program that unpacks entries by hand must check every name: no .. part, no leading / or \, and the full path of the target must stay inside the target folder (the tutorial Paths and the environment). ZipFile.ExtractToDirectory does this check for you; your own loop does not.
What you learned#
ZipArchiveon aMemoryStreamwithleaveOpen,CreateEntry,Entries,GetEntry,Open,Delete,- the archive must be disposed to be complete,
- compression levels, and small files that grow,
- check entry names before you unpack.
Exercises#
- Write
zipFiles(aNames)that returns the bytes of an archive and send them in the web server of the tutorial A tiny web framework. - Write
listArchive(oStream)that returns the entry names as a Ring list. - Compare the five levels for a real text file and a JPEG picture.
- Add a comment to an entry (
Comment) and read it back.