Xceed Real-Time Zip for .NET Documentation
In This Topic
    Creating a Zip archive using ZipWriter - Snippet
    In This Topic

    The following example demonstrates how to create a Zip archive locally using the files in a test directory.

    static void ZipWriterExample()
    {
      string zipFilePath = @"D:\RealTimeZipExamples\MyZipFile.zip";
      // NOTE: The trailing backslash is important, we use it below to build the paths in the zip archive
      string sourceFolder = @"D:\ToZip\";
    
      // Create a stream for a new zip file
      using( FileStream zipFileStream = new FileStream( zipFilePath, FileMode.Create, FileAccess.Write, FileShare.None ) )
      {
        /* Wrapping the ZipWriter object in a 'using' block will make sure the archive is closed
         * properly after we're done adding content. If you use ZipWriter outside a 'using' block,
         * make sure you call ZipWriter.CloseZipFile() to flush the archive's meta data
         * to the output stream. */
    
        // Create the ZipWriter object around the stream
        using( ZipWriter zipWriter = new ZipWriter( zipFileStream ) )
        {
          int index;
          FileInfo sourceFile;
          string sourceFilenameInZip;
    
          /* As a convenience, ZipWriter offers the option to automatically close the output stream when
             ZipWriter is closed. The behavior is disabled by default.
         
             In this example, we will not enable it because we are already closing the zip
             file automatically in the 'using' block above. */
          //zipWriter.AllowOutputStreamClosure = true;
    
          /* Since we'll be adding many files in the archive, we'll create a work buffer
             ahead of time and use it over and over again to avoid creating a new buffer
             each time we read from a source file. */
          int bufferSize = 64 * 1024;
          byte[] buffer = new byte[ bufferSize ];
    
          /* Create a local header object that will be used to specify the path/filename in
             the zip file and other options like compression and encryption. */
          ZipItemLocalHeader localHeader = new ZipItemLocalHeader();
    
          /* Options can be set "globally" before zipping starts.
             We will set the file name for each file inside the loop. The other 
             options have default values that satisfy us:
             The compression method is Deflated at a the 'Normal' compression level
             No encryption.
             No comment. */
          //localHeader.CompressionMethod = CompressionMethod.Deflated;
          //localHeader.CompressionLevel = CompressionLevel.Normal;
          //localHeader.EncryptionMethod = EncryptionMethod.WinZipAes;
          //localHeader.EncryptionPassword = "password";
    
          // Compute the index where the base path ends, minus the trailing backslash
          index = sourceFolder.Length - 1;
    
          // Go through all the files in the source folder and its sub-folders
          foreach( string sourcePath in Directory.EnumerateFiles( sourceFolder, "*", SearchOption.AllDirectories ) )
          {
            // Get file information
            sourceFile = new FileInfo( sourcePath );
    
            // Compute a relative path for the file consisting of the full path minus the base path in 'sourceFolder'
            sourceFilenameInZip = sourcePath.Substring( index );
    
            // Assign the filename in zip in the header
            localHeader.FileName = sourceFilenameInZip;
    
            // Optional. Set the last write date/time in the header
            localHeader.LastWriteDateTime = sourceFile.LastWriteTime;
    
            try
            {
              // Open the current file for sequential reading
              using( Stream sourceFileStream = new FileStream( sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan ) )
              {
                /* If we make it here, the source file has been opened successfully. We can
                   safely add the item to the zip archive. */
    
                // Write the local header for the file in the archive
                zipWriter.WriteItemLocalHeader( localHeader );
    
                // Write the entire stream's content to the archive, using the work buffer we created
                zipWriter.WriteItemData( sourceFileStream, buffer, 0, bufferSize );
              }
            }
            catch( FileNotFoundException )
            {
              /* We're unable to open the source file. We will simply skip it and continue to
                 the next one. */
    
            }
            catch( System.Security.SecurityException )
            {
              /* We're unable to open the source file. We will simply skip it and continue to
                 the next one. */
            }
            catch( DirectoryNotFoundException )
            {
              /* We're unable to open the source file. We will simply skip it and continue to
                 the next one. */
            }
            catch( UnauthorizedAccessException )
            {
              /* We're unable to open the source file. We will simply skip it and continue to
                 the next one. */
            }
            catch( PathTooLongException )
            {
              /* We're unable to open the source file. We will simply skip it and continue to
                 the next one. */
            }
          }
    
          // OPTIONAL: A global comment for the zip archive can be set when closing the archive. By default, there is no comment.
          //ZipEndHeader endHeader = new ZipEndHeader( "Dynamically generated in <unknown> seconds" );
          //zipWriter.CloseZipFile( endHeader );
    
          /* Because we are in a 'using' block, ZipWriter.Dispose() will take care of calling
             ZipWriter.CloseZipFile() for us if we don't do it here.
    
             When using ZipWrite outside of a 'using' block, ZipWriter.CloseZipFile() MUST be
             called explicitly or the zip file will be incomplete and unusable. */
        }
      }
    }
        Private Shared Sub ZipWriterExample()
          Dim zipFilePath As String = "D:\RealTimeZipExamples\MyZipFile.zip"
          ' NOTE: The trailing backslash is important, we use it below to build the paths in the zip archive
          Dim sourceFolder As String = "D:\ToZip\"
    
          ' Create a stream for a new zip file
          Using zipFileStream As New FileStream(zipFilePath, FileMode.Create, FileAccess.Write, FileShare.None)
    '         Wrapping the ZipWriter object in a 'using' block will make sure the archive is closed
    '         * properly after we're done adding content. If you use ZipWriter outside a 'using' block,
    '         * make sure you call ZipWriter.CloseZipFile() to flush the archive's meta data
    '         * to the output stream. 
    
            ' Create the ZipWriter object around the stream
            Using zipWriter As New ZipWriter(zipFileStream)
              Dim index As Integer
              Dim sourceFile As FileInfo
              Dim sourceFilenameInZip As String
    
    '           As a convenience, ZipWriter offers the option to automatically close the output stream when
    '             ZipWriter is closed. The behavior is disabled by default.
    '         
    '             In this example, we will not enable it because we are already closing the zip
    '             file automatically in the 'using' block above. 
              'zipWriter.AllowOutputStreamClosure = true;
    
    '           Since we'll be adding many files in the archive, we'll create a work buffer
    '             ahead of time and use it over and over again to avoid creating a new buffer
    '             each time we read from a source file. 
              Dim bufferSize As Integer = 64 * 1024
              Dim buffer(bufferSize - 1) As Byte
    
    '           Create a local header object that will be used to specify the path/filename in
    '             the zip file and other options like compression and encryption. 
              Dim localHeader As New ZipItemLocalHeader()
    
    '           Options can be set "globally" before zipping starts.
    '             We will set the file name for each file inside the loop. The other 
    '             options have default values that satisfy us:
    '             The compression method is Deflated at a the 'Normal' compression level
    '             No encryption.
    '             No comment. 
              'localHeader.CompressionMethod = CompressionMethod.Deflated;
              'localHeader.CompressionLevel = CompressionLevel.Normal;
              'localHeader.EncryptionMethod = EncryptionMethod.WinZipAes;
              'localHeader.EncryptionPassword = "password";
    
              ' Compute the index where the base path ends, minus the trailing backslash
              index = sourceFolder.Length - 1
    
              ' Go through all the files in the source folder and its sub-folders
              For Each sourcePath As String In Directory.EnumerateFiles(sourceFolder, "*", SearchOption.AllDirectories)
                ' Get file information
                sourceFile = New FileInfo(sourcePath)
    
                ' Compute a relative path for the file consisting of the full path minus the base path in 'sourceFolder'
                sourceFilenameInZip = sourcePath.Substring(index)
    
                ' Assign the filename in zip in the header
                localHeader.FileName = sourceFilenameInZip
    
                ' Optional. Set the last write date/time in the header
                localHeader.LastWriteDateTime = sourceFile.LastWriteTime
    
                Try
                  ' Open the current file for sequential reading
                  Using sourceFileStream As Stream = New FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan)
    '                 If we make it here, the source file has been opened successfully. We can
    '                   safely add the item to the zip archive. 
    
                    ' Write the local header for the file in the archive
                    zipWriter.WriteItemLocalHeader(localHeader)
    
                    ' Write the entire stream's content to the archive, using the work buffer we created
                    zipWriter.WriteItemData(sourceFileStream, buffer, 0, bufferSize)
                  End Using
                Catch e1 As FileNotFoundException
    '               We're unable to open the source file. We will simply skip it and continue to
    '                 the next one. 
    
                Catch e2 As System.Security.SecurityException
    '               We're unable to open the source file. We will simply skip it and continue to
    '                 the next one. 
                Catch e3 As DirectoryNotFoundException
    '               We're unable to open the source file. We will simply skip it and continue to
    '                 the next one. 
                Catch e4 As UnauthorizedAccessException
    '               We're unable to open the source file. We will simply skip it and continue to
    '                 the next one. 
                Catch e5 As PathTooLongException
    '               We're unable to open the source file. We will simply skip it and continue to
    '                 the next one. 
                End Try
              Next sourcePath
              
              ' OPTIONAL: A global comment for the zip archive can be set when closing the archive. By default, there is no comment.
              'Dim endHeader As New ZipEndHeader("Dynamically generated in <unknown> seconds")
              'zipWriter.CloseZipFile(endHeader)
    
              ' Because we are in a 'using' block, ZipWriter.Dispose() will take care of calling
              ' ZipWriter.CloseZipFile() for us if we don't do it here.
    
              '  When using ZipWrite outside of a 'using' block, ZipWriter.CloseZipFile() MUST be
              '  called explicitly or the zip file will be incomplete and unusable.
            End Using
          End Using
        End Sub