How to Zip file folder in C#

By FoxLearn 7/17/2024 4:24:23 AM   9.14K
To compress or zip files, folders using DotNetZip and display a progress bar in a C# Windows Forms application, follow these steps.

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 Studio 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.

DotNetZip is a FAST, FREE class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files.

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.

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language

VIDEO TUTORIAL