Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Bulky Data Is No Problem Thanks to Compression/Decompression in .NET 2.0 : Page 2

If you never need to use compression for your applications, consider yourself lucky. For the rest of us, the good news is that .NET 2.0 has two new classes to handle compression and decompression streams. Find out when, and how, to use these valuable facilities.


advertisement
Handling Compression Events
Now that the main compression and decompression routines are defined, you can code the event handler for the various buttons. The event handler for the Compress button is as follows:

Private Sub btnCompress_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCompress.Click '---used to store the compressed data--- Dim compressedData() As Byte '---compress the data--- If rbGZipStream.Checked Then compressedData = Compress("Gzip", _ System.Text.Encoding.ASCII.GetBytes(txtBefore.Text)) Else compressedData = Compress("Deflate", _ System.Text.Encoding.ASCII.GetBytes(txtBefore.Text)) End If '---copy the compressed data into a string for presentation--- Dim i As Integer Dim s As New System.Text.StringBuilder() For i = 0 To compressedData.Length - 1 If i <> compressedData.Length - 1 Then s.Append(compressedData(i) & " ") Else s.Append(compressedData(i)) End If Next '---show the compressed data as a string--- txtAfter.Text = s.ToString End Sub

The data in the txtBefore control is converted into a byte array and then compressed. The compressed data is then converted to string for display in txtAfter.

The event handler for the Decompress button is as follows:



Private Sub btnDecompress_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDecompress.Click '---format the compressed string into a byte array--- Dim eachbyte() As String = txtAfter.Text.Split(" ") Dim data(eachbyte.Length - 1) As Byte For i As Integer = 0 To eachbyte.Length - 1 data(i) = Convert.ToByte(eachbyte(i)) Next '---decompress the data and shows the decompressed data--- If rbGZipStream.Checked Then txtBefore.Text = System.Text.Encoding.ASCII.GetString( _ Decompress("Gzip", data)) Else txtBefore.Text = System.Text.Encoding.ASCII.GetString( _ Decompress("Deflate", data)) End If End Sub

It converts the data displayed in the txtAfter control into a byte array and then sends it for decompression. The decompressed data is displayed back in the txtBefore control.

The event handler for the Select file to compress button is as follows:

Private Sub btnSelectFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSelectFile.Click '---let user choose a file to compress--- Dim openFileDialog1 As New OpenFileDialog() 'openFileDialog1.InitialDirectory = "c:\" openFileDialog1.Filter = "All files (*.*)|*.*" openFileDialog1.RestoreDirectory = True If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then '---read the content of the file into the byte array--- Dim fileContents As Byte() fileContents = My.Computer.FileSystem.ReadAllBytes(openFileDialog1.FileName) '---create the gzip file--- Dim filename As String = openFileDialog1.FileName & ".gzip" If File.Exists(filename) Then File.Delete(filename) Dim fs As FileStream = _ New FileStream(filename, FileMode.CreateNew, FileAccess.Write) '---compress the content of file--- Dim compressed_Data As Byte() If rbGZipStream.Checked Then compressed_Data = Compress("Gzip", fileContents) Else compressed_Data = Compress("Deflate", fileContents) End If If compressed_Data IsNot Nothing Then '---write the compressed content into the compressed file--- fs.Write(compressed_Data, 0, compressed_Data.Length) fs.Close() End If End If End Sub

It reads the content of the file selected by the user, compresses it, and creates a new file (with the same file name but with a .gzip extension appended) containing the compressed data.

The event handler for the Select file to decompress button is as follows:

Private Sub btnDecompressFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDecompressFile.Click '---let user choose a file to decompress--- Dim openFileDialog1 As New OpenFileDialog() ' openFileDialog1.InitialDirectory = "c:\" openFileDialog1.Filter = "All GZIP files (*.gzip)|*.gzip" openFileDialog1.RestoreDirectory = True If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then '---read the content of the compressed file into byte array--- Dim fileContents As Byte() fileContents = My.Computer.FileSystem.ReadAllBytes(openFileDialog1.FileName) '---decompress the content of file--- Dim uncompressed_Data As Byte() If rbGZipStream.Checked Then uncompressed_Data = Decompress("Gzip", fileContents) Else uncompressed_Data = Decompress("Deflat", fileContents) End If '---create the decompressed file--- Dim filename As String = _ openFileDialog1.FileName.Substring( _ 0, openFileDialog1.FileName.Length - 5) If File.Exists(filename) Then File.Delete(filename) Dim fs As FileStream = _ New FileStream( _ filename, _ FileMode.CreateNew, FileAccess.Write) If uncompressed_Data IsNot Nothing Then '---write the decompressed content into the file--- fs.Write(uncompressed_Data, 0, uncompressed_Data.Length) fs.Close() End If End If End Sub

It reads the content of the file selected by the user, decompresses it, and creates a new file (by stripping its .gzip extension) containing the decompressed data.

Testing the Application
Press F5 to test the application (see Figure 2).

Figure 2. Testing the Application: Select the compression algorithm to use and then you can compress either a text string, or the content of a file.

You should observe the following:

  • Compressing small amount of text will actually result in a larger compressed text.
  • Different text will yield different compression ratio, even though the number of characters is constant.
  • Text files compress the best; they yield the best compression ratio.
  • Other binary files such as .exe, jpg, generally do not compress well and will result in greater than 100 percent% compression ratios, which are worthless.

One important observation is that the implementations of the GZIP and Deflate algorithms in .NET are less efficient (in terms of compression ratios) than other third-party GZIP utilities on the market. While you may be able to compress a 10MB file to 4MB using the .NET classes, you might find that you can get an even smaller compression size using a third-party tool. Also, the compression class cannot work with data larger than 4GB. However, the implementation in .NET will allow you to decompress all files that have been compressed with the other GZIP utilities in the market.

Decompressed
In this article, you have seen how to use compression classes in .NET 2.0. While the implementation is not as efficient as those non-MS solutions in the marketplace, it does provide you with an easy (and free) way to incorporate compression capabilities into your .NET applications!



Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap