How to Zip file folder in C#

By FoxLearn 11/15/2024 9:07:43 AM   9.49K
To compress or zip files, folders using DotNetZip and display a progress bar in a C# Windows Forms application, follow these steps.

DotNetZip is a lightweight and easy-to-use class library for working with .zip files in .NET applications. It enables developers using VB.NET, C#, or any .NET language to easily create, read, and update zip archives.

The library simplifies zip compression tasks and also includes additional features for ZLIB, Deflate, GZIP, and BZip2 compression and decompression. In addition to the core library, DotNetZip provides a GUI tool for zipping, as well as command-line utilities for various compression tasks.

DotNetZip is a versatile library that works on Windows PCs with the full .NET Framework, as well as on Windows Mobile devices using the .NET Compact Framework. It allows developers to create and manipulate zip files using VB, C#, or any .NET language, and can also be used in COM environments like PHP, Classic ASP, or VBScript.

Key features include:

- Creating Zip Archives: Add files or directories to a new archive.

- Reading and Extracting: List files in a zip archive and extract them.

- Modifying Archives: Rename, remove, or add entries to existing zip archives.

- Stream Support: Create zip files from streams, save or extract zip files to streams.

- ASP.NET/Silverlight Integration: Dynamically create zip files from web applications.

DotNetZip offers improved versions of the `DeflateStream` and `GZipStream` classes from the .NET BCL, based on a .NET port of Zlib. These enhanced streams provide better performance and support for customizable compression levels. Additionally, **ZlibStream** is included to fully support RFC 1950, 1951, and 1952, completing the set for advanced compression tasks.

DotNetZip is a 100% managed code library that can be used in any .NET application, including Console, WinForms, WPF, ASP.NET, SharePoint, Web services, and PowerShell scripts. It generates zip files that are fully compatible with Windows Explorer, Java applications, and Linux-based apps, ensuring broad interoperability across platforms.

DotNetZip is a simple, easy-to-use library packaged as a single 400k DLL with no third-party dependencies. It is designed to work in Medium Trust environments, making it suitable for most hosting scenarios. By referencing the DLL, you can easily integrate zipping functionality into your application. The library supports features like zip passwords, Unicode, ZIP64, AES encryption, multiple compression levels, stream input/output, and self-extracting archives.

How to Zip file folder in C#?

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ZipFile" and then click OK

Drag and drop the Label, TextBox, Button, ProgressBar controls from the Visual Toolbox onto your form designer, then design your form as shown below.

c# zip folder

You need to install Ionic.Zip via NuGet Package Manager by right-clicking on your project in Solution Explorer, then select "Manage NuGet Packages...". Search for "Ionic.Zip" and install the package.

Add code to button click event handler as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ZipFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //  folder browser dialog c#
        private void btnFolder_Click(object sender, EventArgs e)
        {
            //Select folder
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "Select your path.";
            if (fbd.ShowDialog() == DialogResult.OK)
                txtFolder.Text = fbd.SelectedPath;
        }

        private void btnFileName_Click(object sender, EventArgs e)
        {
            //Select file name
            using(OpenFileDialog ofd=new OpenFileDialog() { Filter="All files|*.*", ValidateNames = true, Multiselect = false })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                    txtFileName.Text = ofd.FileName;
            }
        }

        // c# zipping files
        private void btnZipFolder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFolder.Text))
            {
                MessageBox.Show("Please select your folder.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFolder.Focus();
                return;
            }
            string path = txtFolder.Text;
            //Zip folder & update progress bar
            Thread thread = new Thread(t =>
              {
                  using(Ionic.Zip.ZipFile zip=new Ionic.Zip.ZipFile())
                  {
                      zip.AddDirectory(path);
                      System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
                      zip.SaveProgress += Zip_SaveProgress;
                      zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName, di.Name));
                  }
              })
            { IsBackground = true };
            thread.Start();
        }

        private void Zip_SaveProgress(object sender, Ionic.Zip.SaveProgressEventArgs e)
        {
            if (e.EventType == Ionic.Zip.ZipProgressEventType.Saving_BeforeWriteEntry)
            {
                progressBar.Invoke(new MethodInvoker(delegate
                {
                    progressBar.Maximum = e.EntriesTotal;
                    progressBar.Value = e.EntriesSaved + 1;
                    progressBar.Update();
                }));
            }
        }

        private void Zip_SaveFileProgress(object sender, Ionic.Zip.SaveProgressEventArgs e)
        {
            if (e.EventType == Ionic.Zip.ZipProgressEventType.Saving_EntryBytesRead)
            {
                progressBar.Invoke(new MethodInvoker(delegate
                {
                    progressBar.Maximum = 100;
                    progressBar.Value = (int)((e.BytesTransferred * 100) / e.TotalBytesToTransfer);
                    progressBar.Update();
                }));
            }
        }

        private void btnZipFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFileName.Text))
            {
                MessageBox.Show("Please select your filename.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFileName.Focus();
                return;
            }
            string fileName = txtFileName.Text;
            //Zip file & update process bar
            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    FileInfo fi = new FileInfo(fileName);
                    zip.AddFile(fileName);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(fileName);
                    zip.SaveProgress += Zip_SaveFileProgress;
                    zip.Save(string.Format("{0}/{1}.zip", di.Parent.FullName, fi.Name));
                }
            })
            { IsBackground = true };
            thread.Start();
        }
    }
}

You can open a file dialog to select files to zip or use the folder browser dialog c# to open your folder to zip, then set up a Thread to perform the zip operation asynchronously.

VIDEO TUTORIAL