Zipping Files and Folders using .Net

It has been almost a year since .NET 4.5 got released. But the problems with most of the recent Microsoft releases have been communication with .NET developers. Only one or two features are known to developers and other features just stay on MSDN and end up becoming simple documents.

For example, the time you ask a .NET developer what is new in the core framework .NET 4.5 most of them will just say async and await

Again it’s very difficult to run through all the new features. Because the features may not sound interesting depending on what you are working currently on..

So in this article I have picked a  nice feature introduced in .NET 4.5 core.

Zip File Creation

Now in .NET we did not have built-in support for implementing Zip compression. Many developers where using third party components like “DotnetZip”,”XceedZip”. In .NET 4.5, the Zip feature is baked in the framework itself, inside the namespace  System.IO.Compression

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

namespace CompressionSample
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ZipButton_Click(object sender, RoutedEventArgs e)
        {
            ZipFile.CreateFromDirectory(@"F:\Pictures\Drawings",@"F:\Images.zip",CompressionLevel.Optimal,includeBaseDirectory:true);
        }
        private void UnzipButton_Click(object sender, RoutedEventArgs e)
        {
            ZipFile.ExtractToDirectory(@"F:\Images.zip",@"F:\Images");
        }
    }
}

The ZipFile class provides static methods for working with zip archives. To use these methods, you must reference the System.IO.Compression.FileSystem assembly in your project. The System.IO.Compression.FileSystem assembly is not available for windows store apps.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s