Skip to main content

.NET C#/VB
Zip Files: All You Need to Know

C#

// AZUL CODING ---------------------------------------
// .NET C#/VB - Zip Files: All You Need to Know
// https://youtu.be/h_xMqbCCyoc


using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.IO.Compression;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;

namespace AzulZipFiles
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Dictionary<string, byte[]> OpenedZipFile = new();
        private readonly ObservableCollection<string> ContentsList = new();

        private static readonly OpenFileDialog OpenDialog = new()
        {
            Title = "Select files",
            Multiselect = true
        };

        private static readonly OpenFileDialog OpenZipDialog = new()
        {
            Title = "Select a zip file",
            Filter = "Zip files (.zip)|*.zip"
        };

        private static readonly SaveFileDialog SaveDialog = new()
        {
            Title = "Save to a zip file",
            Filter = "Zip files (.zip)|*.zip"
        };

        public static readonly CommonOpenFileDialog FolderBrowserDialog = new()
        {
            Title = "Select a folder",
            IsFolderPicker = true,
            Multiselect = false
        };

        public MainWindow()
        {
            InitializeComponent();

            ZipItemsControl.ItemsSource = ContentsList;
        }

        #region Create & Extract

        private void CreateBtn_Click(object sender, RoutedEventArgs e)
        {
            if (FolderBrowserDialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                string folder = FolderBrowserDialog.FileName ?? "";
                string parent = Directory.GetParent(folder)?.FullName ?? "";
                string zip = Path.Combine(parent, "zipfile.zip");

                ZipFile.CreateFromDirectory(folder, zip, CompressionLevel.Optimal, false);
                MessageBox.Show("Zip file created successfully.");
            }
        }

        private void ExtractBtn_Click(object sender, RoutedEventArgs e)
        {
            if (OpenZipDialog.ShowDialog() == true)
            {
                string zip = OpenZipDialog.FileName ?? "";
                string parent = Directory.GetParent(zip)?.FullName ?? "";
                string folder = Path.Combine(parent, "Extracted");

                Directory.CreateDirectory(folder);
                ZipFile.ExtractToDirectory(zip, folder);
                MessageBox.Show("Zip file extracted successfully.");
            }
        }

        #endregion
        #region Read & Edit Contents

        private void OpenBtn_Click(object sender, RoutedEventArgs e)
        {
            ContentsList.Clear();
            OpenedZipFile.Clear();

            if (OpenZipDialog.ShowDialog() == true)
            {
                using ZipArchive zip = ZipFile.Open(OpenZipDialog.FileName, ZipArchiveMode.Read);

                foreach (ZipArchiveEntry entry in zip.Entries)
                {
                    using (Stream stream = entry.Open())
                    {
                        using MemoryStream ms = new();
                        stream.CopyTo(ms);

                        OpenedZipFile.Add(entry.FullName, ms.ToArray());
                    }

                    ContentsList.Add(entry.FullName);
                }
            }
        }

        private void AddFilesBtn_Click(object sender, RoutedEventArgs e)
        {
            if (OpenDialog.ShowDialog() == true)
            {
                foreach (string filepath in OpenDialog.FileNames)
                {
                    string filename = Path.GetFileName(filepath);

                    using FileStream stream = File.OpenRead(filepath);
                    using MemoryStream ms = new();
                    stream.CopyTo(ms);

                    if (OpenedZipFile.ContainsKey(filename))
                    {
                        OpenedZipFile[filename] = ms.ToArray();
                    }
                    else
                    {
                        OpenedZipFile.Add(filename, ms.ToArray());
                        ContentsList.Add(filename);
                    }
                }
            }
        }

        private void RemoveItemBtn_Click(object sender, RoutedEventArgs e)
        {
            string filename = (string)((MenuItem)sender).Tag;
            OpenedZipFile.Remove(filename);
            ContentsList.Remove(filename);
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (SaveDialog.ShowDialog() == true)
            {
                using FileStream zip = new(SaveDialog.FileName, FileMode.Create);
                using ZipArchive archive = new(zip, ZipArchiveMode.Update);

                foreach (KeyValuePair<string, byte[]> file in OpenedZipFile)
                {
                    ZipArchiveEntry entry = archive.CreateEntry(file.Key, CompressionLevel.Optimal);

                    using BinaryWriter writer = new(entry.Open());
                    writer.Write(file.Value);
                }
            }

            MessageBox.Show("Zip file saved successfully.");
        }

        #endregion
    }
}

Enjoying this tutorial?


VB.NET

' AZUL CODING ---------------------------------------
' .NET C#/VB - Zip Files: All You Need to Know
' https://youtu.be/h_xMqbCCyoc


Imports System.IO
Imports System.IO.Compression
Imports Microsoft.Win32
Imports System.Collections.ObjectModel
Imports Microsoft.WindowsAPICodePack.Dialogs

Class MainWindow

    Private ReadOnly OpenedZipFile As New Dictionary(Of String, Byte())
    Private ReadOnly ContentsList As New ObservableCollection(Of String)

    Private Shared ReadOnly OpenDialog As New OpenFileDialog With {
        .Title = "Select files",
        .Multiselect = True
    }

    Private Shared ReadOnly OpenZipDialog As New OpenFileDialog With {
        .Title = "Select a zip file",
        .Filter = "Zip files (.zip)|*.zip"
    }

    Private Shared ReadOnly SaveDialog As New SaveFileDialog With {
        .Title = "Save to a zip file",
        .Filter = "Zip files (.zip)|*.zip"
    }

    Public Shared ReadOnly FolderBrowserDialog As New CommonOpenFileDialog With {
        .Title = "Select a folder",
        .IsFolderPicker = True,
        .Multiselect = False
    }

    Public Sub New()
        InitializeComponent()
        ZipItemsControl.ItemsSource = ContentsList
    End Sub

#Region "Create & Extract"

    Private Sub CreateBtn_Click(sender As Object, e As RoutedEventArgs)
        If FolderBrowserDialog.ShowDialog() = CommonFileDialogResult.Ok Then
            Dim folder As String = FolderBrowserDialog.FileName
            Dim parent As String = Directory.GetParent(folder).FullName
            Dim zip As String = Path.Combine(parent, "zipfile.zip")

            ZipFile.CreateFromDirectory(folder, zip, CompressionLevel.Optimal, False)
            MessageBox.Show("Zip file created successfully.")
        End If
    End Sub

    Private Sub ExtractBtn_Click(sender As Object, e As RoutedEventArgs)
        If OpenZipDialog.ShowDialog() = True Then
            Dim zip As String = OpenZipDialog.FileName
            Dim parent As String = Directory.GetParent(zip)?.FullName
            Dim folder As String = Path.Combine(parent, "Extracted")

            Directory.CreateDirectory(folder)
            ZipFile.ExtractToDirectory(zip, folder)
            MessageBox.Show("Zip file extracted successfully.")
        End If
    End Sub

#End Region
#Region "Read & Edit Contents"

    Private Sub OpenBtn_Click(sender As Object, e As RoutedEventArgs)
        ContentsList.Clear()
        OpenedZipFile.Clear()

        If OpenZipDialog.ShowDialog() = True Then
            Using zip As ZipArchive = ZipFile.Open(OpenZipDialog.FileName, ZipArchiveMode.Read)

                For Each entry As ZipArchiveEntry In zip.Entries
                    Using stream As Stream = entry.Open()
                        Using ms As New MemoryStream()
                            stream.CopyTo(ms)
                            OpenedZipFile.Add(entry.FullName, ms.ToArray())
                        End Using
                    End Using

                    ContentsList.Add(entry.FullName)
                Next
            End Using
        End If
    End Sub

    Private Sub AddFilesBtn_Click(sender As Object, e As RoutedEventArgs)
        If OpenDialog.ShowDialog() = True Then
            For Each filepath As String In OpenDialog.FileNames
                Dim filename As String = Path.GetFileName(filepath)

                Using stream As FileStream = File.OpenRead(filepath)
                    Using ms As New MemoryStream()
                        stream.CopyTo(ms)

                        If OpenedZipFile.ContainsKey(filename) Then
                            OpenedZipFile(filename) = ms.ToArray()
                        Else
                            OpenedZipFile.Add(filename, ms.ToArray())
                            ContentsList.Add(filename)
                        End If
                    End Using
                End Using
            Next
        End If
    End Sub

    Private Sub RemoveItemBtn_Click(sender As Object, e As RoutedEventArgs)
        Dim filename As String = sender.Tag
        OpenedZipFile.Remove(filename)
        ContentsList.Remove(filename)
    End Sub

    Private Sub SaveBtn_Click(sender As Object, e As RoutedEventArgs)
        If SaveDialog.ShowDialog() = True Then
            Using zip As New FileStream(SaveDialog.FileName, FileMode.Create)
                Using archive As New ZipArchive(zip, ZipArchiveMode.Update)

                    For Each file As KeyValuePair(Of String, Byte()) In OpenedZipFile
                        Dim entry As ZipArchiveEntry = archive.CreateEntry(file.Key, CompressionLevel.Optimal)

                        Using writer As New BinaryWriter(entry.Open())
                            writer.Write(file.Value)
                        End Using
                    Next
                End Using
            End Using
        End If

        MessageBox.Show("Zip file saved successfully.")
    End Sub

#End Region

End Class

XAML

<!-- AZUL CODING --------------------------------------- -->
<!-- .NET C#/VB - Zip Files: All You Need to Know -->
<!-- https://youtu.be/h_xMqbCCyoc -->


<Window x:Class="AzulZipFiles.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AzulZipFiles"
        mc:Ignorable="d"
        Title="Zip Files - Azul Coding" Height="400" SizeToContent="Width" ResizeMode="CanMinimize">
    <DockPanel Background="White">
        <Label DockPanel.Dock="Top" Content="Zip file manager" Padding="5,0,5,5" Margin="20" FontWeight="SemiBold" FontSize="16" BorderBrush="DodgerBlue" BorderThickness="0,0,0,2"/>
        <StackPanel DockPanel.Dock="Bottom" Margin="20" Orientation="Horizontal">
            <Button Name="CreateBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="CreateBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/file.png"/>
                    <TextBlock Text="Create" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Button Name="ExtractBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="ExtractBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/archive-folder--v1.png"/>
                    <TextBlock Text="Extract" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Rectangle Width="2" Fill="DodgerBlue" Margin="0,0,10,0"/>
            <Button Name="OpenBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="OpenBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/opened-folder.png"/>
                    <TextBlock Text="Open" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Button Name="AddFilesBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="AddFilesBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/add--v1.png"/>
                    <TextBlock Text="Add files" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Button Name="SaveBtn" Padding="10,5" Background="#f0f0f0" Click="SaveBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/save.png"/>
                    <TextBlock Text="Save" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
        </StackPanel>
        <ScrollViewer Margin="20,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <ItemsControl x:Name="ZipItemsControl" Background="#f0f0f0">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button HorizontalContentAlignment="Stretch" BorderThickness="0" Background="#f0f0f0">
                            <Button.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Click="RemoveItemBtn_Click" Header="Remove" Tag="{Binding}"/>
                                </ContextMenu>
                            </Button.ContextMenu>
                            <StackPanel Orientation="Vertical" Margin="3,3">
                                <TextBlock Text="{Binding}" FontSize="14" TextTrimming="CharacterEllipsis"/>
                            </StackPanel>
                        </Button>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </ScrollViewer>
    </DockPanel>
</Window>