Zip UnZip files using C#

Hi All, today I found a nice feature of C# to compress and un-compress files. Before starting you have to add one DLL in your application. This DLL is already in your system you just have to reference it.

Add Reference to (~/Windows/Microsoft.NET/assembly/GAC_MSIL/System.IO.Compression.FileSystem/(Your .NET Version)

 

using System;
using System.IO;
using System.IO.Compression;
using System.Web.UI;

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnZip_Click(object sender, EventArgs e)
{
string strSource = txtSource.Text;
string strDesctination = txtDestination.Text;
if (Validation(strSource, strDesctination, “zip”))
{
try
{
if (File.Exists(strDesctination))
{
File.Delete(strDesctination);
}
ZipFile.CreateFromDirectory(strSource, strDesctination);
ShowMessage(“Zip file is created successfully.”);
}
catch (Exception ex)
{
ShowMessage(“Error!!!”);
}
}
}
protected void btnUnZip_Click(object sender, EventArgs e)
{
string strSource = txtSource.Text;
string strDesctination = txtDestination.Text;
if (Validation(strSource, strDesctination, “unzip”))
{
try
{
if (Directory.Exists(strDesctination))
{
Directory.CreateDirectory(strDesctination);
}
ZipFile.ExtractToDirectory(strSource, strDesctination);
ShowMessage(“File is unzipped successfully.”);
}
catch (Exception ex)
{
ShowMessage(“Error!!!”);
}
}
}

private bool Validation(string source, string destination, string job)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(destination))
{
ShowMessage(“Please enter valid source and destination path!!!”);
return false;
}
else
{
if (job.Equals(“zip”))
{
if (Directory.Exists(source))
{
return true;
}
}
else if (job.Equals(“unzip”))
{
if (File.Exists(source))
{
return true;
}
}

ShowMessage(“Please enter valid source and destination path!!!”);
return false;
}
}

private void ShowMessage(string message)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), “key”, “alert(‘” + message + “‘)”, true);
}
}

 

 

Advertisements

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 )

Google+ photo

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

Connecting to %s