In this tutorial, I'll show you how to zip a folder using System.IO.Compression in C#. The System.IO.Compression library contains methods that allows you to compress and decompress services for streams.

In order to play the demo, we will create a simple UI that will allow you to select a directory and then compress it to a file as below.

zip folder in c#

You should add a reference to System.IO.Compression.dll, which you can do by right-clicking->add reference->assemblies->framework->System.IO.Compression.dll

Add code to handle your windows forms application as below

using System;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;

namespace AppDesign
{
    public partial class frmZip : Form
    {
        public frmZip()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                if (fbd.ShowDialog() == DialogResult.OK)
                    txtFolder.Text = fbd.SelectedPath;
            }
        }

        private void btnZip_Click(object sender, EventArgs e)
        {
            DirectoryInfo di = new DirectoryInfo(txtFolder.Text);
            string zipFile = $"{di.FullName.Replace(di.Name, "")}{di.Name}.zip";
            ZipFile.CreateFromDirectory(txtFolder.Text, zipFile);
            MessageBox.Show($"File: {di.Name}.zip created successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

The zipFile variable uses the directory name that you want to compress as a compressed file name.