Blue Theme Orange Theme Green Theme Red Theme
 
Dundas Dashboard
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual C# » Zip and Unzip files using GZipStream and DeflateStream classes

Zip and Unzip files using GZipStream and DeflateStream classes

The dot net framework provides us a way to compress and decompress data using the classes under the System.IO.Compression. There are two main classes that perform the job, namely the GZipStream class and the DeflateStream class.

Author Rank:
Technologies: .NET 2.0,Visual C# .NET
Total downloads :
Total page views :  8382
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

The .NET framework provides us a way to compress and decompress data using the classes under the System.IO.Compression. There are two main classes that perform the job, namely the GZipStream class and the DeflateStream class. Both use the same algorithm to compress and decompress data but there are some differences. In fact, GZipStream method supports more formats specifications that DeflateStream method something that renders the compressed files according to the GZipStream more used in a multiplatform context that uses GZip method to compress and decompress files. In the other hand, the Deflate stream method is recommended if we are using compressed and decompressed files in a single platform context for example the same machine is used to compress, decompress and use the handled files at the same time because DeflateStream method, unlike the GZipStream, doesn't support additional information, flags and headers that facilitate the operation across different platforms. Hence, it will be considered are optimal solution for a mono platform.

In this article, I propose this solution that helps to compress and decompress files. First this is a class that uses GZipStream class

using System;

using System.IO;

using System.IO.Compression;

 

namespace appWin

{

/// <summary>

/// This enumeration enables user to precise

/// to select mode zip or unzip

/// </summary>

public enum Action{Zip,UnZip };

/// <summary>

/// This class performs files compression and decompression

/// </summary>

public class GZip

{

/// <summary>

/// This is a private field that represents

/// the full source file path

/// </summary>

private string _SourceFileName ="";

/// <summary>

/// This is a private field that represents

/// the full destination file path

/// </summary>

private string _DestinationFileName ="";

/// <summary>

/// This byte array is used to stock both

/// The input file contents and out put file

/// contents as bytes

/// </summary>

private byte[] oBuffer;

/// <summary>

/// This is the class responsible of

/// zipping and unzipping files

/// </summary>

private GZipStream oZipper;

/// <summary>

/// This is a default constructor

/// </summary>

public GZip() { }

/// <summary>

/// This is an overloaded constructor

/// </summary>

/// <param name="SourceFileName">This represents the

/// full source file name of the one going to be zipped

/// </param>

/// <param name="DestinationFileName">This represents the

/// full source file name of the one going to be unziped

/// </param>

/// <param name="action">Choose between zip or unzip mode</param>

public GZip(string SourceFileName, string DestinationFileName,Action action)

{

oZipper = null;

this.SourceFileName = SourceFileName;

this.DestinationFileName = DestinationFileName;

/* The user only precizes the zip mode

or the desired action in order to be performed

* instead of using the method directly that is

marked as protected, take a look below */

if (action == Action.Zip)

{ this.CompressFile(); }

if (action == Action.UnZip)

{ this.DecompressFile(); }

 

}

/// <summary>

/// This is the source file full path property

/// </summary>

public string SourceFileName

{

get

{

return _SourceFileName;

}

set

{

_SourceFileName = value;

}

}

/// <summary>

/// This is the destination full path property

/// </summary>

public string DestinationFileName

{

get

{

return _DestinationFileName;

}

set

{

_DestinationFileName = value;

 

}

}

/// <summary>

/// This is the method responsible for compression, it is marked

/// as protected because we use it is called at the constructor

/// level when a compression mode is chosen instead of using it directly

/// </summary>

protected void CompressFile()

{

 

if (File.Exists(SourceFileName))

{     

using (FileStream inputFile = File.Open(SourceFileName, FileMode.Open), outputFile = File.Create(DestinationFileName))

{

using (oZipper = new GZipStream(outputFile, CompressionMode.Compress))

{

    oBuffer = new byte[inputFile.Length];

    int counter = 0;

    while ((counter = inputFile.Read(oBuffer, 0, oBuffer.Length)) != 0)

    {

        oZipper.Write(oBuffer, 0, counter);

    }

}

oBuffer = null;

}

}

//TO DO here notify user that the task is performed

}

/// <summary>

/// This is the method responsible for compression, it is marked

/// as protected because we use it is called at the constructor

/// level when a decompression mode is chosen instead of using it directly

/// </summary>

protected void DecompressFile()

{

 

if (File.Exists(SourceFileName))

{

using (FileStream inputFile = File.Open(SourceFileName, FileMode.Open), outputFile = File.Create(DestinationFileName))

{

using (oZipper = new GZipStream(inputFile, CompressionMode.Decompress))

{

oBuffer = new byte[inputFile.Length];

int counter;

while ((counter = oZipper.Read(oBuffer, 0, oBuffer.Length)) != 0)

{

    outputFile.Write(oBuffer, 0, counter);

}

}

oBuffer = null;

}

}

MessageBox.Show("Decompression done");

}

}

//TO DO here notify user that the task is performed

 

}

Now, in order to consume the class service here you is the code

private void button1_Click(object sender, EventArgs e)

{

  GZip oZip = new GZip(@"C:\Test.txt", @"C:\Test1.txt", Action.Zip);

  oZip = new GZip(@"C:\Test1.txt", @"C:\Test2.txt", Action.UnZip);

}

This is another class but that uses DeflateStream class:

using System;

using System.IO;

using System.IO.Compression;

 

namespace appWin

{

/// <summary>

/// This enumeration enables user to precise

/// to select mode zip or unzip

/// </summary>

public enum Action{Zip,UnZip };

/// <summary>

/// This class performs files compression and decompression

/// </summary>

public class Deflat

{

/// <summary>

/// This is a private field that represents

/// the full source file path

/// </summary>

private string _SourceFileName ="";

/// <summary>

/// This is a private field that represents

/// the full destination file path

/// </summary>

private string _DestinationFileName ="";

/// <summary>

/// This byte array is used to stock both

/// The input file contents and out put file

/// contents as bytes

/// </summary>

private byte[] oBuffer;

/// <summary>

/// This is the class responsible of

/// zipping and unzipping files

/// </summary>

private DeflateStream oZipper;

/// <summary>

/// This is a default constructor

/// </summary>

public Deflat() { }

/// <summary>

/// This is an overloaded constructor

/// </summary>

/// <param name="SourceFileName">This represents the

/// full source file name of the one going to be zipped

/// </param>

/// <param name="DestinationFileName">This represents the

/// full source file name of the one going to be unziped

/// </param>

/// <param name="action">Choose between zip or unzip mode</param>

public Deflat(string SourceFileName, string DestinationFileName,Action action)

{

oZipper = null;

this.SourceFileName = SourceFileName;

this.DestinationFileName = DestinationFileName;

/* The user only precizes the zip mode

or the desired action in order to be performed

* instead of using the method directly that is

marked as protected, take a look below */

if (action == Action.Zip)

{ this.CompressFile(); }

if (action == Action.UnZip)

{ this.DecompressFile(); }

 

}

/// <summary>

/// This is the source file full path property

/// </summary>

public string SourceFileName

{

get

{

return _SourceFileName;

}

set

{

_SourceFileName = value;

}

}

/// <summary>

/// This is the destination full path property

/// </summary>

public string DestinationFileName

{

get

{

return _DestinationFileName;

}

set

{

_DestinationFileName = value;

 

}

}

/// <summary>

/// This is the method responsible for compression, it is marked

/// as protected because we use it is called at the constructor

/// level when a compression mode is chosen instead of using it directly

/// </summary>

protected void CompressFile()

{

 

if (File.Exists(SourceFileName))

{     

using (FileStream inputFile = File.Open(SourceFileName, FileMode.Open), outputFile = File.Create(DestinationFileName))

{

using (oZipper = new DeflateStream(outputFile, CompressionMode.Compress))

{

    oBuffer = new byte[inputFile.Length];

    int counter = 0;

    while ((counter = inputFile.Read(oBuffer, 0, oBuffer.Length)) != 0)

    {

        oZipper.Write(oBuffer, 0, counter);

    }

}

oBuffer = null;

}

}

MessageBox.Show("Compression done");

}

/// <summary>

/// This is the method responsible for compression, it is marked

/// as protected because we use it is called at the constructor

/// level when a decompression mode is chosen instead of using it directly

/// </summary>

protected void DecompressFile()

{

 

if (File.Exists(SourceFileName))

{

using (FileStream inputFile = File.Open(SourceFileName, FileMode.Open), outputFile = File.Create(DestinationFileName))

{

using (oZipper = new DeflateStream(inputFile, CompressionMode.Decompress))

{

oBuffer = new byte[inputFile.Length];

int counter;

while ((counter = oZipper.Read(oBuffer, 0, oBuffer.Length)) != 0)

{

    outputFile.Write(oBuffer, 0, counter);

}

}

oBuffer = null;

}

}

// TO DO here notify the user that the action is performed

}

}

}

Now, in order to consume the class service here you is the code

private void button1_Click(object sender, EventArgs e)

{

  GZip oZip = new GZip(@"C:\Test.txt", @"C:\Test1.txt", Action.Zip);

  oZip = new GZip(@"C:\Test1.txt", @"C:\Test2.txt", Action.UnZip);

}

I have marked the methods compress and decompress as protected in order do not to be used directly, instead in provide the choice for the developer via the enumeration Action to choose witch mode will be used and then the both methods are triggered from the constructor. This is more simple and elegant from my point of view.

Finally, and in order to provide more flexibility and more possibilities for developers to extend the both classes you can extract an interface as below:

using System;

namespace appWin

{

    interface IZipUnZip

    {

        /// <summary>

        /// This is the full path of the source path

        /// </summary>

        string DestinationFileName { get; set; }

        /// <summary>

        /// This is the full path of the destination path

        /// </summary>

        string SourceFileName { get; set; }

    }

}

Then make the both classes implement this interface

/// <summary>

/// This class performs files compression and decompression

/// </summary>

public class Deflat : appWin.IZipUnZip

{

.

.

.

/// <summary>

/// This class performs files compression and decompression

/// </summary>

public class Deflat : appWin.IZipUnZip

{

.

.

.

That's it

Good Dotneting!!!


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved