ComponentOne Zip for .NET
Zip for .NET Tutorials / Handling Zip Files
In This Topic
    Handling Zip Files
    In This Topic

    This tutorial shows how you can handle zip files, including the following operations:

    Here is what the final application will look like:


    Note: This is a very simple application, designed to highlight the main functionality of the C1ZipFile object. The distribution disk also includes a more sophisticated version, which supports more advanced features such as drag and drop, zipping folders, setting the compression level, and so on.

    Step 1: Create the main form.

    Start a new Visual Studio project.

    1. From the Toolbox, add the following controls to the form:
      • Seven Button controls along the left edge of the form, as shown in the picture above. In the Properties window make the following changes to each Button control:
        Button Button.Text Property Button.Name Property
        1 Create Zip File… btnNew
        2 Open Zip File… btnOpen
        3 Add Files… btnAdd
        4 Extract Files btnExtract
        5 Remove Files btnRemove
        6 View File btnView
        7 Test Zip File btnTest
      • A ListView control covering the right part of the form. In the Properties window, click on the ellipsis button next to the Columns property. The ColumnHeader Collection Editor dialog box appears.

      Note: The Column Header Collection Editor can also be accessed by clicking Edit Columns in the ListView Tasks menu. To access the ListView Tasks menu, click the smart tag () in the upper right corner of the ListView control.

    2. Click the Add button to add five ColumnHeaders, and then set the Text property of each column to File, Date, Size, Compressed, and Amount, respectively.

      Here is what the ColumnHeader Collection Editor should look like:


    3. Select OK to close the editor box.

      Note that to view the column headers, in the Properties window set the View property to Details or in the ListView Tasks menu, select Details from the View drop-down box.


    Step 2: Add a reference to the C1Zip assembly.

    Go to the Solution Explorer window, right-click on References, and select the Add Reference menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.2.dll file.

    Select the Form1.vb tab (Form1.cs in C#) or go to View|Code to open the Code Editor. At the top of the file, add the following directives:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Imports System.IO
    Imports C1.C1Zip
    

    To write code in C#

    C#
    Copy Code
    using System.IO;
    using C1.C1Zip;
    

    This makes the objects defined in the C1Zip and System.IO assemblies visible to the project.

    Step 3: Declare a C1ZipFile object.

    Switch to the Code Editor and type (or copy) the following data member declaration:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private m_Zip As C1ZipFile
    

    To write code in C#

    C#
    Copy Code
    private m_Zip As C1ZipFile;
    

    This is the main object in this application. It implements the methods used to handle zip files.

    Step 4: Add code to initialize the C1ZipFile object.

    Add the following code to the Form_Load event:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
          ' Create the C1ZipFile member.
        m_Zip = New C1ZipFile()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void Form1_Load(object sender, EventArgs e)
    {
      // Create the C1ZipFile member.
        m_Zip = new C1ZipFile();
    }
    

    This code creates a new C1ZipFile object and assigns it to the m_Zip member. Note that the C1ZipFile object cannot be used yet. It needs to be attached to an existing zip file first using the Open method (or to a new one using the Create method).

    Step 5: Add code to create a zip file.

    Add the following code to handle the Click event for the Create Zip File command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
         ' Show open file dialog.
        Dim fo As SaveFileDialog = New SaveFileDialog()
        fo.FileName = "*.zip"
        If fo.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If
         ' Open zip file.
        Try
            m_Zip.Create(fo.FileName)
        Catch
            MessageBox.Show("Can't create ZIP file, please try again.", "C1Zip")
        End Try
         ' Update display.
        UpdateDisplay()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnNew_Click(object sender, EventArgs e)
    {
        // Show open file dialog. 
        SaveFileDialog fo = new SaveFileDialog();
        fo.FileName = "*.zip";
        if (fo.ShowDialog() != DialogResult.OK ) return;
         // Open zip file. 
        try
        {
            m_Zip.Create(fo.FileName);
        }
        catch
        {
            MessageBox.Show("Can't create ZIP file, please try again.", "C1Zip");
        }
         // Update display. 
        UpdateDisplay();
    }
    

    Step 6: Add code to open a zip file.

    Add the following code to handle the Click event for the Open Zip File command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnOpen_Click(sender As Object, e As EventArgs) Handles btnOpen.Click
         ' Show open file dialog.
        Dim fo As OpenFileDialog = New OpenFileDialog()
        fo.FileName = "*.zip"
        If fo.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
        Try
            m_Zip.Open(fo.FileName)
        Catch
            MessageBox.Show("Invalid ZIP file, please try again.")
        End Try
          ' Update display.
        UpdateDisplay()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnOpen_Click(object sender, EventArgs e)
    {
         // Show open file dialog.
        OpenFileDialog fo = new OpenFileDialog();
        fo.FileName = "*.zip";
        if (fo.ShowDialog() != DialogResult.OK ) return;
        try
        {
            m_Zip.Open(fo.FileName);
        }
        catch
        {
            MessageBox.Show("Invalid ZIP file, please try again.");
        }
         // Update display.
        UpdateDisplay();
    }
    

    The main line calls the Open method on the C1ZipFile object to attach the object to an existing zip file. Note the use of a Try/Catch statement, mainly to handle situations where the use selects a file that is not a zip file.

    After opening the file, the code calls the UpdateDisplay utility function to display the contents of the zip file.

    Step 7: Add code to update the display.

    Next, add the UpdateDisplay utility function to display the contents of the zip file:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub UpdateDisplay()
         ' Update the ListView control to show the zip file contents.
        With ListView1
             ' Remove any existing items.
            .Items.Clear()
             ' Add each entry.
            Dim ze As C1ZipEntry
            For Each ze In m_Zip.Entries
                 ' Calculate the compression amount.
                Dim pct As Double = 0
                If ze.SizeUncompressed > 0 Then
                    pct = 1 - ze.SizeCompressed / ze.SizeUncompressed
                End If
                 ' Build ListView item.
                Dim items(4) As String
                items(0) = ze.FileName
                items(1) = Format(ze.Date, "MM/dd/yy")
                items(2) = Format(ze.SizeUncompressed, "#,##0")
                items(3) = Format(ze.SizeCompressed, "#,##0")
                items(4) = Format(pct, "00 %")
                Dim lvi As ListViewItem = New ListViewItem(items)
                 ' Save ZipEntry into item tag.
                lvi.Tag = ze
                 ' Add item to ListView.
                .Items.Add(lvi)
            Next ze
             ' Update UI.
            Dim hasEntries As Boolean = (.Items.Count > 0)
            btnExtract.Enabled = hasEntries
            btnRemove.Enabled = hasEntries
            btnTest.Enabled = hasEntries
        End With
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void UpdateDisplay()
    {
         // Remove any existing items.
        listView1.Items.Clear();
         // Add each entry.
        foreach (C1ZipEntry ze in m_Zip.Entries)
        {
            // Calculate the compression amount.
            double pct = 0;
            if (ze.SizeUncompressed > 0)
            {
                pct = 1 - (((double)ze.SizeCompressed) / ((double)ze.SizeUncompressed));
            }
            // Build ListView item.
            ListViewItem lvi = new ListViewItem(new string[] { ze.FileName, Microsoft.VisualBasic.Strings.Format(ze.Date, "MM/dd/yy"), Microsoft.VisualBasic.Strings.Format(ze.SizeUncompressed, "#,##0"), Microsoft.VisualBasic.Strings.Format(ze.SizeCompressed, "#,##0"), Microsoft.VisualBasic.Strings.Format(pct, "00 %") });
            // Save ZipEntry into item tag.
            lvi.Tag = ze;
            // Add item to ListView.
            listView1.Items.Add(lvi);
        }
        // Update UI.
        bool hasEntries = (listView1.Items.Count > 0);
        btnExtract.Enabled = hasEntries;
        btnRemove.Enabled = hasEntries;
        btnTest.Enabled = hasEntries;
    }
    

    The main lines start by declaring a C1ZipEntry object and using it in a ForEach loop over the entries in the zip file (m_Zip.Entries).

    For each entry, the function creates a ListViewItem containing the information extracted from the C1ZipEntry object and adds the new entry to the ListView control. Note that the C1ZipEntry object itself is also saved in the Tag property of the ListView items.

    Finally, the code enables or disables the command buttons depending on whether or not there are entries available to be extracted, removed or tested.

    Step 8: Add code to test the integrity the zip file.

    Add the following code to handle the Click event for the Test Zip File command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
         ' Test each entry.
        Dim ze As C1ZipEntry
        For Each ze In m_Zip.Entries
            If Not ze.CheckCRC32() Then
                MessageBox.Show("** Entry " & ze.FileName & " has errors.", "C1Zip", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
        Next
         ' If we got here, everything is OK.
        MessageBox.Show("All entries passed CRC check", "C1Zip")
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnTest_Click(object sender, EventArgs e)
    {
         // Test each entry.
        foreach (C1ZipEntry ze in m_Zip.Entries)
        {
            if (!ze.CheckCRC32())
            {
                MessageBox.Show("** Entry " + ze.FileName + " has errors.", "C1Zip", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        } 
         // If we got here, everything is OK.
        MessageBox.Show("All entries passed CRC check", "C1Zip");
    }
    

    The main lines declare a C1ZipEntry variable and use it to loop over the entries in the zip file. The routine then calls the CheckCRC32 method on each entry to check whether the actual checksum of the bytes stored in the file matches the checksum stored in the entry header. The function returns true if the values match and false if they don't (which indicates the entry is corrupted).

    Step 9: Add code to view the contents of an entry.

    Add the following code to handle the Click event for the View File command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
         ' Get the first selected item that is not a directory.
        Dim ze As C1ZipEntry = Nothing
        Dim lvi As ListViewItem
        For Each lvi In ListView1.SelectedItems
            Dim zeItem As C1ZipEntry = lvi.Tag
            If (zeItem.Attributes And FileAttributes.Directory) = 0 Then
                ze = zeItem
                Exit For
            End If
        Next lvi
         ' Make sure we got something.
        If ze Is Nothing Then
            MessageBox.Show("Sorry, no files to show...", "C1Zip")
            Exit Sub
        End If
         ' Read entry content into a string.
        Dim entry As Stream = ze.OpenReader()
        Dim sr As StreamReader = New StreamReader(entry)
        Dim entryText As String = sr.ReadToEnd()
        entry.Close()
         ' Make sure the entry is not too big for the MessageBox.
        If entryText.Length > 16000 Then
            entryText = entryText.Substring(0, 16000)
        End If
         ' Show the entry in the message box.
        MessageBox.Show(entryText, ze.FileName)
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnView_Click(object sender, EventArgs e)
    {
         // Get the first selected item that is not a directory.
        C1ZipEntry ze = null;
        foreach (ListViewItem lvi in listView1.SelectedItems)
        {
            C1ZipEntry zeItem = lvi.Tag as C1ZipEntry;
            if ((zeItem.Attributes == 0) && (FileAttributes.Directory == 0))
            {
                ze = zeItem;
                break;
            }
        }
         // Make sure we got something.
        if (ze == null )
        {
            MessageBox.Show("Sorry, no files to show...", "C1Zip");
            return;
        }
         // Read entry content into a string.
        Stream entry = ze.OpenReader();
        StreamReader sr = new StreamReader(entry);
        string  entryText = sr.ReadToEnd();
        entry.Close();
         // Make sure the entry is not too big for the MessageBox.
        if (entryText.Length > 16000 ) 
        {
            entryText = entryText.Substring(0, 16000);
        }
         // Show the entry in the message box.
        MessageBox.Show(entryText, ze.FileName);
    }
    

    The function starts by choosing the first selected zip entry that is not a subdirectory. If a valid entry cannot be found, the function exits.

    The function then calls the OpenReader method to obtain a Stream that can be used to read the contents of the entry. There are no temporary files or additional delays involved in this step; the data is expanded as it is read from the stream.

    Next, the function reads the entry content directly into a string using the ReadToEnd method on the StreamReader object, then closes the stream.

    Finally, the string is truncated and displayed in a message box.

    Note that this function was designed to show the contents of short text files. If you try to view the contents of binary files, it will show only a couple of characters.

    Step 10: Add code to add entries to the zip file.

    Add the following code to handle the Click event for the Add Files command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
         ' Get list of files to add.
        Dim fo As OpenFileDialog = New OpenFileDialog()
        fo.Multiselect = True
        fo.FileName = "*.*"
        If fo.ShowDialog <> Windows.Forms.DialogResult.OK Then Exit Sub
         ' Add files in the list.
        Dim file As String
        For Each file In fo.FileNames()
            m_Zip.Entries.Add(file)
        Next file
         ' Done.
        UpdateDisplay()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnAdd_Click(object sender, EventArgs e)
    {
         // Get list of files to add.
        OpenFileDialog fo = new OpenFileDialog();
        fo.Multiselect = true;
        fo.FileName = "*.*";
        if (fo.ShowDialog() == DialogResult.OK)
        {
             // Add files in the list.
            foreach (string file in fo.FileNames)
            {
                m_Zip.Entries.Add(file);
            }
             // Done.
            UpdateDisplay();
        }
    }
    

    Adding new entries to a zip file is easy. The main line simply calls the Add method on the C1ZipFile object, passing a string that contains the full name of the file to be added. That’s all there is to it.

    Step 11: Add code to extract a zip entry.

    Add the following code to handle the Click event for the Extract Files command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnExtract_Click(sender As Object, e As EventArgs) Handles btnExtract.Click
         ' Make sure we have some selected entries.
        Dim cnt As Integer = ListView1.SelectedIndices.Count
        If cnt = 0 Then
            MessageBox.Show("Sorry, no files to extract...", "C1Zip")
            Exit Sub
        End If
         ' Confirm with user.
        Dim dr As DialogResult
        Dim msg As String
        msg = "Please confirm that you want to extract " + cnt.ToString() + " entries."
        dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
        If dr <> Windows.Forms.DialogResult.OK Then Exit Sub
         ' Extract all selected entries
        Dim lvi As ListViewItem
        Dim ze As C1ZipEntry
        For Each lvi In ListView1.SelectedItems
            ze = lvi.Tag
            If ze.SizeCompressed > 0 Then
                 m_Zip.Entries.Extract(ze.FileName)
            End If
        Next lvi
         ' Done.
        UpdateDisplay()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnExtract_Click(object sender, EventArgs e)
    {
         // Make sure we have some selected entries.
        int cnt = listView1.SelectedIndices.Count;
        if (cnt == 0)
        {
            MessageBox.Show("Sorry, no files to extract...", "C1Zip");
            return;
        }
         // Confirm with user.
        DialogResult dr;
        string  msg;
        msg = "Please confirm that you want to extract " + cnt.ToString() + " entries.";
        dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        if ( dr != DialogResult.OK )  return;
         // Extract all selected entries.
        C1ZipEntry ze;
        foreach (ListViewItem lvi in ListView1.SelectedItems)
        {
            ze = (C1ZipEntry)lvi.Tag;
            if ( ze.SizeCompressed > 0 )
            {
                m_Zip.Entries.Extract(ze.FileName);
            }
        }
         // Done.
        UpdateDisplay();
    }
    

    The most important line calls the Extract method on the Entries property of the C1ZipFile object. The parameter is the string that contains the file name of the entry (which is stored in the entry's FileName property).

    By default, the Extract method expands the entry and saves it in the same directory where the zip file is located. There are other versions of this method that allow you to specify the destination directory and file name for the expanded file. For more details, see the C1.C1Zip Namespace section.

    Step 12: Add code to remove entries from the zip file.

    Add the following code to handle the Click event for the Remove Files command button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
         ' Make sure we have some selected entries.
        Dim cnt As Integer = ListView1.SelectedIndices.Count
        If cnt = 0 Then
            MessageBox.Show("Oops, no files to remove...", "C1Zip")
            Exit Sub
        End If
         ' Confirm with user.
        Dim dr As DialogResult
        Dim msg As String
        msg = "Please confirm that you want to delete " + cnt.ToString() + " entries."
        dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
        If dr <> Windows.Forms.DialogResult.OK Then Exit Sub
         ' Delete all selected entries.
        Dim lvi As ListViewItem
        Dim ze As C1ZipEntry
        For Each lvi In ListView1.SelectedItems
            ze = lvi.Tag
            m_Zip.Entries.Remove(ze.FileName)
        Next lvi
         ' Done.
        UpdateDisplay()
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnRemove_Click(object sender, EventArgs e)  {
         // Make sure we have some selected entries.
        int cnt = listView1.SelectedIndices.Count;
        if (cnt == 0 )
        {
            MessageBox.Show("Oops, no files to remove...", "C1Zip");
            return;
        }
         // Confirm with user.
         DialogResult dr;
        string  msg;
        msg = "Please confirm that you want to delete " + cnt.ToString() + " entries.";
        dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        if (dr != DialogResult.OK) return;
         // Delete all selected entries.
        foreach (ListViewItem lvi in listView1.SelectedItems)
        {
            C1ZipEntry ze = (C1ZipEntry)lvi.Tag;
            if (ze.SizeCompressed > 0)
            {
                m_Zip.Entries.Remove(ze.FileName);
            }
        } 
         // Done.
        UpdateDisplay();
    }
    

    The most important line calls the Remove method on the Entries property of the C1ZipFile object. The parameter is the string that contains the file name of the entry (which is stored in the entry's FileName property).

    This concludes the Handling Zip Files tutorial.