SIGN UP MEMBER LOGIN:    
ARTICLE

Compress and Decompress data using GZipStream

Posted by Kirtan Patel Articles | Algorithms in C# April 10, 2010
This article guides you how to compress the data using GZipStream in C#.
Reader Level:
Download Files:
 

::Introduction ::

Article will teach you about how to Compress the data with GZipStream Class of .net

Technology :

CSharp .net 2.0/3.5

:: Implementation ::

For simple compression and decompression of data we will use GZipStream class of the .NET.

In this article,  I will explain how to compress and decompress data by building small sample application.


 

So lets import the following namespaces in your application. 

using System.IO;

using System.IO.Compression;


Here when working with GZipStream we need to specify Stream to Open for writing as first argument and CompressionMode as second argument that specifies weather we want to Compress the Data or Decompress the data we can do this by Specifying enumeration CompressMode.Compress or CompressMode.Decompress as second argument of the GZipStream Class object.

Here in example I am compressing textdata into file test.zip file and reread it from the created test.zip file.

private void btnCompressData_Click(object sender, EventArgs e)

        {

            //Write Data To Zip File

            string data = txtData.Text;

            GZipStream outStream = new GZipStream(File.OpenWrite("test.zip"), CompressionMode.Compress);

            StreamWriter sw = new StreamWriter(outStream);

            sw.Write(data);

            sw.Close();

            MessageBox.Show("Data Compressed to file test.zip!!");

            txtData.Text = "";

        }


:: explanation of above code ::

In first line of Compressing Data Part I have stored the data to be written in variable "data" from textBox now in second line creates a new GZipStream class and As constructor argument of that object of GZipStream we have passed File.OpenWrite("test.zip") which will return FileStream object associated with "test.zip" file and in Second argument we have passed CompressionModel.Compress as we want to compress the data ..

now We have created one StreamWriter object to write the data to GZipStream object we have by using Write() method of the StreamWriter class we can write data to the GZipStream object

and finally we have closed the StreamWriter Object to end the writing

 private void btnDecompressData_Click(object sender, EventArgs e)

        {

           //Read the Data From zip

            string ReadData = "";

            GZipStream instream = new GZipStream(File.OpenRead("test.zip"), CompressionMode.Decompress);

 

            StreamReader reader = new StreamReader(instream);

 

            ReadData = reader.ReadToEnd();

            reader.Close();

            txtData.Text = ReadData;

            MessageBox.Show("Data Read Successfully!!");

 

        }


Same kind of logic is there for reading data also we open the test.zip file using GZipStream object and read the data in stream using ReadToEnd() method and displayed the read data to the TextBox again. and closed the StreamReader object.

That's it :)

:: Conclusion ::


This article explains how to compress and decompress data using GZipStream class of .NET.

Login to add your contents and source code to this article
share this article :
post comment
 

Thank you for replying, but the problem 1 I can't find the solution for it. Can you explain why ?

Posted by Luu Tai Oct 04, 2010

          //decompress the data
                MemoryStream compressed = new MemoryStream(Buffer);
                MemoryStream uncompressed = new MemoryStream();
                using (GZipStream s = new GZipStream(compressed,CompressionMode.Decompress))
                    {
                       
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                          {
                            size = s.Read(data, 0, data.Length);
                             if (size > 0)
                                {
                                   uncompressed.Write(data, 0, size);
                                }
                                else
                                    {
                                    break;
                                    }
                                }
                           
                    }

Posted by Tshifhiwa Mudzusi Sep 29, 2010

I have 2 problems

1. File's size is bigger after being compressed
2. I can't open a file after being decompressed

this is my snipe code:

FileStream fromFile = File.OpenRead("c:\\1.pdf");
            FileStream toFile = File.Create("c:\\1.zaz");

            GZipStream gZipStream = new GZipStream(toFile, CompressionMode.Compress);

            int mybyte = fromFile.ReadByte();
            while (mybyte != -1)
            {
                gZipStream.WriteByte((byte)mybyte);
                mybyte = fromFile.ReadByte();
            }
            Console.WriteLine("Compress completely");
            gZipStream.Close();


            // Gi?i nén file

            fromFile = File.OpenRead("c:\\1.zaz");
            toFile = File.Create("c:\\2.pdf");

            gZipStream = new GZipStream(fromFile, CompressionMode.Decompress);

            mybyte = gZipStream.ReadByte();
            while (mybyte!=-1)
            {
                toFile.WriteByte((byte)mybyte);
                mybyte = gZipStream.ReadByte();
            }
            gZipStream.Close();

            Console.Write("Decompress completely");
            Console.ReadLine();

May i code something wrong ?

Posted by Luu Tai Sep 25, 2010

I previously wrote this article: http://www.c-sharpcorner.com/uploadfile/GemingLeader/programmatically-compress-and-decompress-files/.

Posted by Mohammad Elsheimy Apr 11, 2010
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor