Friday 6 February 2015

How to zip and unzip a folder/file using C#

Welcome to Logically Proven Blog.
This post teaches you how to zip and unzip a folder/file using C#.

It has been a year since .NET Framework 4.5 got released.
Due to lack of communication from Microsoft releases, .Net developers are unaware of the important features listed in latest frameworks.
 
These are some good features available in .Net Framework 4.5.
Feature 1: async and await
Feature 2: Zip Facility (Zip compression)
Feature 3: Regex Timeout (Time Out)
Feature 4: Profile Optimization (Improved start-up performance)
Feature 5: Garbage Collector (background cleanup)
 
Only one or two features are known to developers and other features just stay on MSDN and end up like archived 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 (at least with people whom I have interacted have just talked about those features).
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.
 
Now this post going to explain the feature 2, i.e., Zip facility (Zip compression). Without awaiting you much, let get into details.

Zip is one of the most accepted archive file formats. Zip format is supported in almost all operating systems with some built-in name.
 
In Windows operating system it’s implemented by the name “Compressed folders”.
In MAC OS it’s implemented by the name Archive utility”.
 
Now in .NET we did not have built-in support for implementing Zip compression. Many developers where using third party components like “DotnetZip”.

In .NET 4.5, the Zip feature is baked in the framework itself, inside the namespace System.IO.Compression.
 
The first step is you need to reference two namespaces:
 
System.IO.Compression.FileSystem
System.IO.Compression
 
The next step is to add the below two namespaces in your .cs file:
 
using System.IO;
using System.IO.Compression;
 
ZipFile is a class provides static methods for creating, extracting, and opening zip archives.
 
If you want to Zip files from a folder you can use the CreateFromDirectory function as shown below:
 
ZipFile.CreateFromDirectory(@"D:\data",@"D:\data.zip");
 
If you wish to unzip, you can use the ExtractToDirectory function as shown in the below code.
 
ZipFile.ExtractToDirectory(@"D:\data.zip", @"D:\data\unzip");
 
 
For more details on this topic:

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Logically Proven
learn, teach, share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.