Lost Password?

  #1 (permalink)  
Old 05-13-2008, 04:52 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Age: 26
Posts: 5,864
Last Blog:
Performance or Maintai...
Rep Power: 20
Jordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud of
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Tutorial: Visual Studio 2008 C# Compressing

COMPRESSING AND DECOMPRESSING FILES WITH C#


1. INTRODUCTION


In this tutorial our subject will be the compression and decompression of files. With the .Net environment you can compress and decompress files by using the open-source compression format GZIP. Besides that, you can also compress files with the DEFLATE algorithm. The two methods are identical in the compression process but GZIP also adds some extra information which results in slightly larger files sizes. If you want to archive your data only through .Net applications you can use the DEFLATE stream class. Otherwise, you should prefer the GZip stream class for compatibility with the popular open source Gzip application.


2. GRAPHICAL USER INTERFACE

For this tutorial the graphical user interface doesn’t provide us with much useful functions, so you can create a console-based project but for simplicity we will create a typical form with a button and an openFileDialog so as to choose which file you want to compress. You can also try importing a saveFileDialog so as to be able to choose the destination of the compressed or extracted file. For this tutorial we will choose the input, the text file to be compressed, but the output will be a pre-specified file.


Picture 1. Our light-weight form



3. CODE DEVELOPMENT

In order to write to or read from a file in your disk you need to create stream objects that do the actual writing/reading process. With stream objects you can write to a resource such as the memory or a particular file. For the compression of a file you need a compression stream. These streams are in the “System.IO.Compression” namespace. These streams behave differently than other streams since they can only read from or write to other streams. So, you need to create one stream for the reading of a file, one for the writing and one compression stream to compress the data that the writing stream gets. The compression stream targets the writing stream. The next step is to read the file and send chunks of data to the compression stream which automatically forwards the compressed data to the writing stream.

The next snippet of code demonstrates the declaration of the three streams:

Code:
private void button1_Click(object sender, EventArgs e)

            {

                openFileDialog1.Filter = "txt files |*.txt";

                if (openFileDialog1.ShowDialog() == DialogResult.OK)

                {

                    FileStream source = File.OpenRead(openFileDialog1.FileName);

                    FileStream destination = File.Create(@"E:\stream.gz");

                    GZipStream myCompressionStream = new GZipStream(destination, CompressionMode.Compress);
The first line of code filters the openDialog’s contents to display only text files. If the user correctly chose a file to open then the three streams are created. The source is the stream that will be compressed. The destination is the compressed file and the “myCompressionStream” comes between the two other streams. As you can see the CompressionMode has been set to “Compress”. When we will decompress the file this parameter will be set to “Decompress”.

Now it is time to read the source one byte at a time and write the compressed data to the output, as shown here:

Code:
int myByte = source.ReadByte();

                    while (myByte != -1)

                    {

                        myCompressionStream.WriteByte((byte)myByte);

                        myByte = source.ReadByte();

                    }

                    destination.Close();
When the method “ReadByte” returns “-1” it means that it has reached the end of file. So we read and compress data one byte at a time until the integer named “myByte” has a value different than “-1”. The compression of the file has been completed.

To perform the decompressing algorithm we must, again define the streams that will perform the decompression. This time the Gzip stream wraps around the compressed file named here “dest2”. The destination of the compress process becomes the source in the decompression method. We use the ReadByte() method of the Gzip DecompressionStream to read and decompress the data. Next we send the decompressed data to the FileStream used for writing the new output file.

Code:
// Start Decompressing

                     FileStream dest2 = File.OpenRead(@"E:\stream.gz");

                     GZipStream myDecompressionStream = new GZipStream(dest2, CompressionMode.Decompress);

                     FileStream ExtractedFile = File.Create(@"E:\extracted.txt");

                     int mySecondByte = myDecompressionStream.ReadByte();

                     while (mySecondByte != -1)

                     {

                         ExtractedFile.WriteByte((byte)mySecondByte);

                         mySecondByte = myDecompressionStream.ReadByte();

                     }

                     source.Close();

                     destination.Close();

                     ExtractedFile.Close();

                }

            }
After the process is over we must close all streams in order to free our files for use by other streams/processes. If you wanted to compress and decompress the files with the DEFLATE method you would only have to change the “GZipStream” to a “DeflateStream” to accomplish your goal. However, bear in mind that these algorithms can process data up to 4GB.


Need Help?
Ask your questions here or create a new thread in the appropriate forum!
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
Don't hesitate to ask any questions that you have! Check out our ASCII Calculator!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
Reply

Tags
compressing, compression, visual studio 2008



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Visual Studio 2008: C# Hello World Tutorial Jordan CSharp Tutorials 4 08-22-2008 10:44 AM
Tutorial: Visual Studio 2008 Obfuscating with Dotfuscator Jordan Tutorials 0 02-08-2008 02:01 PM


All times are GMT -5. The time now is 11:30 PM.

Contest Stats

John ........ 223.00000
dargueta ........ 168.00000
Xav ........ 164.00000
gaylo565 ........ 18.00000
WingedPanther ........ 15.00000
|pH| ........ 15.00000
Johnnyboy ........ 3.00000
navghost ........ 1.00000

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 66%

Ads