Xceed Real-Time Zip for .NET Documentation
Extracting data from a Zip archive using ZipReader
Welcome to Xceed Real-Time Zip for .NET, .NET Standard & Xamarin > Task-Based Help > Extracting data from a Zip archive using ZipReader
 Example: Extracting data from a Zip archive using ZipReader on desktop environments

The following example shows how to read a Zip archive on desktop environments.

static void ZipReaderExample()

{

  string zipFilePath = @"D:\RealTimeZipExamples\MyZipFile.zip";

  string destinationFolder = @"D:\UnzipToFolder";

  string password = "password";



  int bufferSize = 64 * 1024;

  byte[] buffer = new byte[ bufferSize ];



  // Create a stream for the zip file

  using( Stream zipFileStream = new FileStream( zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan ) )

  {

    // Create a local header object

    ZipItemLocalHeader localHeader = new ZipItemLocalHeader();



    // Create the ZipReader object around the stream

    using( ZipReader zipReader = new ZipReader( zipFileStream ) )

    {

      // Optional. Provide the default password for encrypted items in the archive

      zipReader.EncryptionPassword = password;



      // Optional. Subscribe to available events

      zipReader.ByteProgression += new EventHandler<ZipReaderByteProgressionEventArgs>( OnByteProgression );

      zipReader.InvalidPassword += new EventHandler<ZipReaderInvalidPasswordEventArgs>( OnInvalidPassword );



      // While the reader finds local headers

      while( zipReader.ReadItemLocalHeader( localHeader ) != null )

      {

        // The 'FileName' property contains the sub-folders and filename

        string outputPath = destinationFolder + localHeader.FileName;

        string outputFolder = Path.GetDirectoryName( outputPath );



        // Make sure the output folder exists

        Directory.CreateDirectory( outputFolder );



        // If the item isn't a folder entry

        if( !localHeader.IsFolder )

        {

          // Create/overwrite an output file using our calculated filename

          using( FileStream outputFileStream = new FileStream( outputPath, FileMode.Create, FileAccess.Write, FileShare.None ) )

          {

            // Have the reader read the item data and write it to the stream using our buffer

            zipReader.ReadItemData( outputFileStream, buffer, 0, bufferSize );

          }

        }

      }

    }

  }

}



private static void OnInvalidPassword( object sender, ZipReaderInvalidPasswordEventArgs e )

{

  // TODO: We have access to the current item being unzipped. We can report it's name, etc

  ZipItemLocalHeader currentItem = e.ZipItemLocalHeader;



  // TODO: We're given the password that failed. We can report it, etc

  string oldPassword = e.OldPassword;



  /* If 'e.NewPassword' is set to null or an empty string, or 'e.Abort' is set to true,

  a ZipReaderException will be thrown for failure to decrypt the item.

  Since items can't be skipped, the entire unzip process will be canceled.

   

  When the event is triggered, 'e.NewPassword' is set to an empty string and 'e.Abort' is set

  to false. */



  // TODO: We have to supply a new password.

  // If that new password is invalid, the event will be triggered again

  e.NewPassword = "Some New Password";



  // TODO: We can ask the entire unzip operation to be aborted

  e.Abort = true;

}



private static void OnByteProgression( object sender, ZipReaderByteProgressionEventArgs e )

{

  // TODO: We have access to the current item being unzipped. We can report it's name, etc

  ZipItemLocalHeader currentItem = e.ZipItemLocalHeader;



  // TODO: We're given the current amount of bytes unzipped for the item. We can report it, etc

  long bytesProcessed = e.BytesProcessed;



  /* Do not assume that e.UncompressedSize and e.Percent will contain useful values.

  Since ZipReader doesn't seek in the archive, it cannot always know the uncompressed

  size in advance. */

}
    Private Shared Sub ZipReaderExample()

      Dim zipFilePath As String = "D:\RealTimeZipExamples\MyZipFile.zip"

      Dim destinationFolder As String = "D:\UnzipToFolder"

      Dim password As String = "password"



      Dim bufferSize As Integer = 64 * 1024

      Dim buffer(bufferSize - 1) As Byte



      ' Create a stream for the zip file

      Using zipFileStream As Stream = New FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan)

        ' Create a local header object

        Dim localHeader As New ZipItemLocalHeader()



        ' Create the ZipReader object around the stream

        Using zipReader As New ZipReader(zipFileStream)

          ' Optional. Provide the default password for encrypted items in the archive

          zipReader.EncryptionPassword = password



          ' Optional. Subscribe to available events

          AddHandler zipReader.ByteProgression, AddressOf OnByteProgression

          AddHandler zipReader.InvalidPassword, AddressOf OnInvalidPassword



          ' While the reader finds local headers

          Do While zipReader.ReadItemLocalHeader(localHeader) IsNot Nothing

            ' The 'FileName' property contains the sub-folders and filename

            Dim outputPath As String = destinationFolder & localHeader.FileName

            Dim outputFolder As String = Path.GetDirectoryName(outputPath)



            ' Make sure the output folder exists

            Directory.CreateDirectory(outputFolder)



            ' If the item isn't a folder entry

            If (Not localHeader.IsFolder) Then

              ' Create/overwrite an output file using our calculated filename

              Using outputFileStream As New FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None)

                ' Have the reader read the item data and write it to the stream using our buffer

                zipReader.ReadItemData(outputFileStream, buffer, 0, bufferSize)

              End Using

            End If

          Loop

        End Using

      End Using

    End Sub



    Private Shared Sub OnInvalidPassword(ByVal sender As Object, ByVal e As ZipReaderInvalidPasswordEventArgs)

      ' TODO: We have access to the current item being unzipped. We can report it's name, etc

      Dim currentItem As ZipItemLocalHeader = e.ZipItemLocalHeader



      ' TODO: We're given the password that failed. We can report it, etc

      Dim oldPassword As String = e.OldPassword



'       If 'e.NewPassword' is set to null or an empty string, or 'e.Abort' is set to true,

'      a ZipReaderException will be thrown for failure to decrypt the item.

'      Since items can't be skipped, the entire unzip process will be canceled.

'       

'      When the event is triggered, 'e.NewPassword' is set to an empty string and 'e.Abort' is set

'      to false. 



      ' TODO: We have to supply a new password.

      ' If that new password is invalid, the event will be triggered again

      e.NewPassword = "Some New Password"



      ' TODO: We can ask the entire unzip operation to be aborted

      e.Abort = True

    End Sub



    Private Shared Sub OnByteProgression(ByVal sender As Object, ByVal e As ZipReaderByteProgressionEventArgs)

      ' TODO: We have access to the current item being unzipped. We can report it's name, etc

      Dim currentItem As ZipItemLocalHeader = e.ZipItemLocalHeader



      ' TODO: We're given the current amount of bytes unzipped for the item. We can report it, etc

      Dim bytesProcessed As Long = e.BytesProcessed



'       Do not assume that e.UncompressedSize and e.Percent will contain useful values.

'      Since ZipReader doesn't seek in the archive, it cannot always know the uncompressed

'      size in advance. 

    End Sub
 Example: Extracting data from a Zip archive using ZipReader on Xamarin (Android and iOS)

The following example shows how to read a Zip archive on Xamarin (Android and iOS).

static void ZipReaderExampleXamarin( Stream zipFileStream )

{

  string password = "password";



  /* If we'll be extracting many items from 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 write to a destination. */



  int bufferSize = 64 * 1024;

  byte[] buffer = new byte[ bufferSize ];



  Dictionary<string, MemoryStream> extractedFiles = new Dictionary<string, MemoryStream>();



  /* NOTE: The zip file can be any type of stream you use. A network stream, a file stream, etc

      The component will never call Stream.Seek() on the stream and will only read to it.

    

      This example will use the 'zipFileStream' memory stream used in the ZipWriter example. */



  // Make sure the zip file stream is positioned at the start

  zipFileStream.Seek( 0, SeekOrigin.Begin );



  // Create a local header object that will be reused

  ZipItemLocalHeader localHeader = new ZipItemLocalHeader();



  // Create the ZipReader object around the stream

  using( ZipReader zipReader = new ZipReader( zipFileStream ) )

  {

    /* As a convenience, ZipReader offers the option to automatically close the input stream when

        ZipReader is closed. The behavior is disabled by default.

     

        In this example, we will not enable it as we may want to manipulate the zip file

        after it has been read. */

    //zipReader.AllowInputStreamClosure = true;



    // Optional. Provide the default password for encrypted items in the archive

    zipReader.EncryptionPassword = password;



    // Optional. Subscribe to available events

    zipReader.ByteProgression += new EventHandler<ZipReaderByteProgressionEventArgs>( OnByteProgression );

    zipReader.InvalidPassword += new EventHandler<ZipReaderInvalidPasswordEventArgs>( OnInvalidPassword );



    /* Here, we supply the local header object we created above.

        ReadItemLocalHeader() will fill the object with current data and return a

        reference to the same object.

        

        ReadItemLocalHeader() can also be called without parameters. Then, it will

        create a new ZipItemLocalHeader object and return it with current data. */



    // While the reader finds local headers

    while( zipReader.ReadItemLocalHeader( localHeader ) != null )

    {

      /* NOTE: 'localHeader.FileName' will contain a leading slash */



      // If the item isn't a folder entry

      if( !localHeader.IsFolder )

      {

        /* NOTE: The destination data can be any type of stream you need. A network stream, a file stream, etc

            The component will never call Stream.Seek() on the stream and will only write to it.

   

            This example will use memory data to keep it simple and on point. */

        MemoryStream outputStream = new MemoryStream();

        

        extractedFiles.Add( localHeader.FileName, outputStream );



        // Have the reader read the item data and write it to the stream using our buffer

        zipReader.ReadItemData( outputStream, buffer, 0, bufferSize );

      }

    }

  }

}



private static void OnInvalidPassword( object sender, ZipReaderInvalidPasswordEventArgs e )

{

  // TODO: We have access to the current item being unzipped. We can report it's name, etc

  ZipItemLocalHeader currentItem = e.ZipItemLocalHeader;



  // TODO: We're given the password that failed. We can report it, etc

  string oldPassword = e.OldPassword;



  /* If 'e.NewPassword' is set to null or an empty string, or 'e.Abort' is set to true,

  a ZipReaderException will be thrown for failure to decrypt the item.

  Since items can't be skipped, the entire unzip process will be canceled.

   

  When the event is triggered, 'e.NewPassword' is set to an empty string and 'e.Abort' is set

  to false. */



  // TODO: We have to supply a new password.

  // If that new password is invalid, the event will be triggered again

  e.NewPassword = "Some New Password";



  // TODO: We can ask the entire unzip operation to be aborted

  e.Abort = true;

}



private static void OnByteProgression( object sender, ZipReaderByteProgressionEventArgs e )

{

  // TODO: We have access to the current item being unzipped. We can report it's name, etc

  ZipItemLocalHeader currentItem = e.ZipItemLocalHeader;



  // TODO: We're given the current amount of bytes unzipped for the item. We can report it, etc

  long bytesProcessed = e.BytesProcessed;



  /* Do not assume that e.UncompressedSize and e.Percent will contain useful values.

  Since ZipReader doesn't seek in the archive, it cannot always know the uncompressed

  size in advance. */

}
    Private Shared Sub ZipReaderExampleXamarin(ByVal zipFileStream As Stream)

      Dim password As String = "password"



'       If we'll be extracting many items from 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 write to a destination. 



      Dim bufferSize As Integer = 64 * 1024

      Dim buffer(bufferSize - 1) As Byte



      Dim extractedFiles As Dictionary(Of String, MemoryStream) = New Dictionary(Of String, MemoryStream)()



'       NOTE: The zip file can be any type of stream you use. A network stream, a file stream, etc

'          The component will never call Stream.Seek() on the stream and will only read to it.

'        

'          This example will use the 'zipFileStream' memory stream used in the ZipWriter example. 



      ' Make sure the zip file stream is positioned at the start

      zipFileStream.Seek(0, SeekOrigin.Begin)



      ' Create a local header object that will be reused

      Dim localHeader As New ZipItemLocalHeader()



      ' Create the ZipReader object around the stream

      Using zipReader As New ZipReader(zipFileStream)

'         As a convenience, ZipReader offers the option to automatically close the input stream when

'            ZipReader is closed. The behavior is disabled by default.

'         

'            In this example, we will not enable it as we may want to manipulate the zip file

'            after it has been read. 

        'zipReader.AllowInputStreamClosure = true;



        ' Optional. Provide the default password for encrypted items in the archive

        zipReader.EncryptionPassword = password



        ' Optional. Subscribe to available events

        AddHandler zipReader.ByteProgression, AddressOf OnByteProgression

        AddHandler zipReader.InvalidPassword, AddressOf OnInvalidPassword



'         Here, we supply the local header object we created above.

'            ReadItemLocalHeader() will fill the object with current data and return a

'            reference to the same object.

'            

'            ReadItemLocalHeader() can also be called without parameters. Then, it will

'            create a new ZipItemLocalHeader object and return it with current data. 



        ' While the reader finds local headers

        Do While zipReader.ReadItemLocalHeader(localHeader) IsNot Nothing

          ' NOTE: 'localHeader.FileName' will contain a leading slash 



          ' If the item isn't a folder entry

          If (Not localHeader.IsFolder) Then

'             NOTE: The destination data can be any type of stream you need. A network stream, a file stream, etc

'                The component will never call Stream.Seek() on the stream and will only write to it.

'       

'                This example will use memory data to keep it simple and on point. 

            Dim outputStream As New MemoryStream()



            extractedFiles.Add(localHeader.FileName, outputStream)



            ' Have the reader read the item data and write it to the stream using our buffer

            zipReader.ReadItemData(outputStream, buffer, 0, bufferSize)

          End If

        Loop

      End Using

    End Sub



    Private Shared Sub OnInvalidPassword(ByVal sender As Object, ByVal e As ZipReaderInvalidPasswordEventArgs)

      ' TODO: We have access to the current item being unzipped. We can report it's name, etc

      Dim currentItem As ZipItemLocalHeader = e.ZipItemLocalHeader



      ' TODO: We're given the password that failed. We can report it, etc

      Dim oldPassword As String = e.OldPassword



'       If 'e.NewPassword' is set to null or an empty string, or 'e.Abort' is set to true,

'      a ZipReaderException will be thrown for failure to decrypt the item.

'      Since items can't be skipped, the entire unzip process will be canceled.

'       

'      When the event is triggered, 'e.NewPassword' is set to an empty string and 'e.Abort' is set

'      to false. 



      ' TODO: We have to supply a new password.

      ' If that new password is invalid, the event will be triggered again

      e.NewPassword = "Some New Password"



      ' TODO: We can ask the entire unzip operation to be aborted

      e.Abort = True

    End Sub



    Private Shared Sub OnByteProgression(ByVal sender As Object, ByVal e As ZipReaderByteProgressionEventArgs)

      ' TODO: We have access to the current item being unzipped. We can report it's name, etc

      Dim currentItem As ZipItemLocalHeader = e.ZipItemLocalHeader



      ' TODO: We're given the current amount of bytes unzipped for the item. We can report it, etc

      Dim bytesProcessed As Long = e.BytesProcessed



'       Do not assume that e.UncompressedSize and e.Percent will contain useful values.

'      Since ZipReader doesn't seek in the archive, it cannot always know the uncompressed

'      size in advance. 

    End Sub