Creating a zip file in memory

Glossary Item Box

Introduction

This topic demonstrates how to create a zip file in memory.

Basic steps

To create a zip file in memory, the following steps must be performed:

    • Retrieve a reference to a folder whose files will be added to the zip file using either the DiskFolder, ZippedFolder, ZipArchive, MemoryFolder or IsolatedFolder classes. With Xceed Zip for .NET, a folder is a folder; it does not matter if it is located within a zip file, on disk or in memory. 

    • Retrieve a reference to a new or existing zip file using the ZipArchive class. Because we want the zip file to reside in memory, we will use a MemoryFile in the constructor of the ZipArchive class. 

    • Call the CopyFilesTo method to copy the entire contents of the folder to the zip file.

Demonstration

This example demonstrates how to copy the contents of a folder located on disk to a zip file located in memory.

VB.NET Copy Code

Imports Xceed.Zip
Imports Xceed.FileSystem

' Note: Pathnames must be modified for code snippets to work under the .NET Compact Framework.

Dim folder As New DiskFolder("c:\windows\fonts")
Dim memFile As New MemoryFile("RAM_File", "fonts.zip")
Dim zip As New ZipArchive(memFile)

folder.CopyFilesTo( zip, false, true )

' Once the zip file has been created, if you want to convert it
' to a byte array, the following code can be used:

Dim baZip() As Byte
Dim memStream As New MemoryStream()

Dim s As Stream = memFile.OpenRead()

Dim buffer(1024) As Byte
Dim bytesRead As Integer

Do
   bytesRead = s.Read(buffer, 0, buffer.Length)

   If bytesRead > 0 Then
      memStream.Write(buffer, 0, bytesRead)
   End If
Loop Until bytesRead = 0

s.Close()

' Get the byte array from the memory stream
baZip = memStream.ToArray()
memStream.Close()

C# Copy Code
using Xceed.Zip;
using Xceed.FileSystem;
using System.IO;
 
// Note: Pathnames must be modified for code snippets to work under the .NET Compact Framework.
 
DiskFolder folder = new DiskFolder( @"c:\windows\fonts" );
MemoryFile memFile = new MemoryFile( "RAM_File", "fonts.zip" );
ZipArchive zip = new ZipArchive( memFile );
 
folder.CopyFilesTo( zip, false, true );
 
// Once the zip file has been created, if you want to convert it
// to a byte array, the following code can be used:
 
byte[] baZip;
 
using( MemoryStream memStream = new MemoryStream() )
{
   using( Stream s = memFile.OpenRead() )
   {
      byte[] buffer = new byte[ 1024 ];
      int bytesRead;
 
      while( ( bytesRead = s.Read( buffer, 0, buffer.Length ) ) > 0 )
      {
         memStream.Write( buffer, 0, bytesRead );
      }
   }
 
   // Get the byte array from the memory stream
   baZip = memStream.ToArray();
}
 

Things you should consider

The main questions you should ask yourself when copying items to a zip file are:

All zip files will automatically be created in the Zip64 zip file format if the limitations of the regular Zip format are reached.