[]
        
(Showing Draft Content)

Compressing and Decompressing Files

The Zip library provides classes that are designed to compress uploaded files into your database and thereby reduce the saved data size. You can also decompress zip files and restore it to its original state with C1.Zip.

In this topic, you will learn how to compress and decompress files using C1.Zip library.

The snapshot depicts an application that uses two button controls and a list view control. The button control events are used to show the compress and decompression of files, while the list view displays the content of the zip file.

App UI with buttons and listview

Note that with the Zip library, a user can compress and decompress different types of files, be it in image file format (jpg, png, gif, tif, or bmp), .docx file format, .xlsx,file format, .txt file format or .pdf file formats.

Compressing Files

The C1.Zip library provides the Create method in C1ZipFile class, which creates an empty zip file on the disk. This method uses the fileName parameter, which is the name of the zip file to create, including the path. If a zip file by the same name already exists, the Create method deletes the old zip files and adds the new one.

Let's say, we want to compress files at a location to this zip file. For this, the user will need to get the location of application directory by using the ExecutablePath property of the Application class using the System.Windows.Forms namespace. All the files in the specified directory are populated in the zip file using the GetFile property of the Directory class using System.IO namespace and the Add method of C1ZipEntryCollection class that uses the fileName parameter, which is nothing but the name of the file to add to the zip file. The user can also call other overload Add methods depending upon the parameters and data types required.

WinForms

This is the C# Code for compressing and decompressing files in WinForms applications:

private void btnCompress_Click(object sender, EventArgs e)
{
    // create zip file
    zip.Create(@"C:\temp\txtfile.zip");
    // get app dir
    string s = Application.ExecutablePath;
    s = s.Substring(0, s.IndexOf(@"\bin")) + @"\resources";
    // populate zip file and list

    foreach (string f in Directory.GetFiles(s))
    {
        string FileName = f.ToLower();
        if (FileName.EndsWith("zip")) continue; // skip self
        listView1.Items.Add(Path.GetFileName(FileName)); // add to list
        zip.Entries.Add(FileName); // add to zip file
    }
    // Update display.
    UpdateDisplay();
}
private void UpdateDisplay()
{
    // Remove any existing items.
    listView1.Items.Clear();
    // Add each entry.
    foreach (C1ZipEntry ze in 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);           
}

This is the VB Code for compressing and decompressing files in WinForms applications:

Private Sub btnCompress_Click(sender As Object, e As EventArgs) Handles btnCompress.Click
    'Create Zip file
    zip.Create("C:\temp\txtfile.zip")
    Dim s As String = Application.ExecutablePath
    s = s.Substring(0, s.IndexOf("\bin")) & "\resources"
    For Each f As String In Directory.GetFiles(s)
        Dim FileName As String = f.ToLower()
        If FileName.EndsWith("zip") Then Continue For
        listView1.Items.Add(Path.GetFileName(FileName))
        'Add files
        zip.Entries.Add(FileName)
    Next
    ' Done.
    UpdateDisplay()
End Sub
Private Sub UpdateDisplay()
    ' Remove any existing items.
    listView1.Items.Clear()
    ' Add each entry.
    For Each ze As C1ZipEntry In zip.Entries
        Dim pct As Double = 0
        ' Calculate the compression amount.
        If ze.SizeUncompressed > 0 Then
            pct = 1 - ((CDbl(ze.SizeCompressed)) / (CDbl(ze.SizeUncompressed)))
        End If
        ' Build ListView item.
        Dim lvi As ListViewItem = 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)
    Next
    ' Update UI.
    Dim hasEntries As Boolean = (listView1.Items.Count > 0)
End Sub

WPF

This is the C# code for compressing and decompressing files in WPF applications:

private void BtnCompress_Click(object sender, RoutedEventArgs e)
{
    // Create the C1ZipFile member.
          zip = new C1ZipFile();
    // Create zip file
          zip.Create(@"C:\temp\txtfile.zip");
    // Get app dir
          string s = System.Reflection.Assembly.GetExecutingAssembly().Location;
    s = s.Substring(0, s.IndexOf(@"\bin")) + @"\resources";
    // Populate zip file and list
          foreach (string f in Directory.GetFiles(s))
    {
        string FileName = f.ToLower();
        // Skip self
              if (FileName.EndsWith("zip")) continue;
        listView1.Items.Add(System.IO.Path.GetFileName(FileName));
        // Add password for each entry that is compressed
              zip.Entries.Add(FileName); // add to zip file
          }
    // Done.
          UpdateDisplay();
}
void UpdateDisplay()
{
    var sel = listView1.SelectedItem;
    listView1.ItemsSource = null;
    if (zip == null)
    {
        return;
    }
    //_flex.ItemsSource = _zip.Entries;
          if (zip.Entries.Count == 0)
    {
        zip = null;
    }
    listView1.SelectedItem = sel;
}

This is the VB code for compressing and decompressing files in WPF applications:

Private Sub BtnCompress_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ' Create the C1ZipFile member.
       zip = New C1ZipFile()
    ' Create zip file
       zip.Create("C:\temp\txtfile.zip")
    ' Get app dir
       Dim s As String = Assembly.GetExecutingAssembly().Location
    s = s.Substring(0, s.IndexOf("\bin")) & "\resources"
    ' Populate zip file and list
       For Each f As String In Directory.GetFiles(s)
        Dim FileName As String = f.ToLower()
        ' Skip self
           If FileName.EndsWith("zip") Then Continue For
        Me.listView1.Items.Add(IO.Path.GetFileName(FileName))
        ' Add password for each entry that is compressed
           zip.Entries.Add(FileName) ' add to zip file
       Next
    ' Done.
       UpdateDisplay()
End Sub
Private Sub UpdateDisplay()
    Dim sel = Me.listView1.SelectedItem
    Me.listView1.ItemsSource = Nothing
    If zip Is Nothing Then
        Return
    End If
    '_flex.ItemsSource = _zip.Entries;
       If zip.Entries.Count = 0 Then
        zip = Nothing
    End If
    Me.listView1.SelectedItem = sel
End Sub

The UpdateDisplay utility function is called to display the contents of the zip file in the List View control.

Decompressing Files

The Zip library provides the Extract method in C1ZipEntryCollection class to extract files from the current zip file, which uses the fileName parameter, which denotes the names of the entry to be extracted. The class also provides many other overloads of the Extract method.

WinForms

This is the C# Code for compressing and decompressing files in WinForms applications:

private void btnDecompress_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)
        {
            zip.Entries.Extract(ze.FileName);
        }
    }
    // Done.
    UpdateDisplay();
}

This is the VB Code for compressing and decompressing files in WinForms applications:

Private Sub btnExpand_Click(sender As Object, e As EventArgs) Handles btnExpand.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")
        Return
    End If
    Dim dr As DialogResult
    Dim msg As String
    ' Confirm with user.
    msg = "Please confirm that you want to extract " & cnt.ToString() & " entries."
    dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
    If dr <> DialogResult.OK Then Return
    ' Extract all selected entries.
    Dim ze As C1ZipEntry
    For Each lvi As ListViewItem In listView1.SelectedItems
        ze = CType(lvi.Tag, C1ZipEntry)
        If ze.SizeCompressed > 0 Then
            zip.Entries.Extract(ze.FileName)
        End If
    Next
    ' Done.
    UpdateDisplay()
End Sub

WPF

This is the C# code for compressing and decompressing files in WPF applications:

private void BtnDecompress_Click(object sender, RoutedEventArgs e)
{
    //Make sure we have some selected entries.
    int cnt = listView1.SelectedItems.Count;
    if (cnt == 0)
    {
        MessageBox.Show("Sorry, no files to extract...", "C1Zip");
        return;
    }
    // Confirm with user.
    MessageBoxResult dr;
    string msg;
    msg = "Please confirm that you want to extract " + cnt.ToString() + " entries.";
    dr = MessageBox.Show(msg, "C1Zip", MessageBoxButton.OKCancel, MessageBoxImage.Question);
    if (dr != MessageBoxResult.OK) return;
    //Extract all selected entries.
    C1ZipEntry ze;
    foreach (string lvi in listView1.SelectedItems)
    {
        ze = (C1ZipEntry)zip.Entries[lvi];
        if (ze.SizeCompressed > 0)
        {
            zip.Entries.Extract(ze.FileName);
        }
    }
    MessageBox.Show("Files extracted !!!");
    // Done.
    UpdateDisplay();
}

This is the VB code for compressing and decompressing files in WPF applications:

Private Sub BtnDecompress_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    'Make sure we have some selected entries.
    Dim cnt As Integer = Me.listView1.SelectedItems.Count
    If cnt = 0 Then
        MessageBox.Show("Sorry, no files to extract...", "C1Zip")
        Return
    End If
    ' Confirm with user.
    Dim dr As MessageBoxResult
    Dim msg As String
    msg = "Please confirm that you want to extract " & cnt.ToString() & " entries."
    dr = MessageBox.Show(msg, "C1Zip", MessageBoxButton.OKCancel, MessageBoxImage.Question)
    If dr <> MessageBoxResult.OK Then Return
    'Extract all selected entries.
    Dim ze As C1ZipEntry
    For Each lvi As String In Me.listView1.SelectedItems
        ze = zip.Entries(lvi)
        If ze.SizeCompressed > 0 Then
            zip.Entries.Extract(ze.FileName)
        End If
    Next
    MessageBox.Show("Files extracted !!!")
    ' Done.
    UpdateDisplay()
End Sub

See Also

Compressing and Decompressing Folders

Password Protecting Zip Files