Compression and Decompression of Files using Visual Basic 2005
page 5 of 9
by Abhishek Kumar Singh
Feedback
Average Rating: 
Views (Total / Last 10 Days): 95186/ 116

Test GZipStream functionality with a Windows application

To test the above mentioned functions, create a windows application in VB 2005 and add two text box controls on the form. Name these as txtFilePath and txtDestainationFolder. Add two labels for these text boxes and change their Text property as "File to Compress/Decompress" and "Destination Folder."

Add two command buttons and name these as btnCompress and btnDecompress and change its Text property to "Compress file" and "Decompress Zipped file" respectively.

Add two more command buttons with name "btnBrowseFile" and " btnBrowseFolder." Specify Text property as "Browse" for both.

Listing 6 – Compression and Decompression windows form snap shot

Add a class files CComp.vb in the application and implement the compression function CompressByte as given in Listing1 above. Add one more class file CDcomp.vb and implement the decompression function DecompressByte as given in Listing 3.

Implement click event of btnCompress.

Listing 7 –Click event implementation of button btnCompress

Private Sub btnCompress_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) _
Handles btnCompress.Click
 
  Dim byteSource() As Byte
  Dim byteCompressed() As Byte
  Dim oCCompression As New CComp
 
  ' Validate paths
  If IO.File.Exists(txtFilePath.Text) = False Then
    MsgBox("Please specify the valid file path to compress", MsgBoxStyle.OkOnly)
    txtFilePath.Focus()
    Exit Sub
  Else
    If IO.Directory.Exists(txtDestainationFolder.Text) = False Then
      MsgBox("Please specify the valid path of destination folder", MsgBoxStyle.OkOnly)
      txtDestainationFolder.Focus()
      Exit Sub
    End If
  End If
 
  Try
  Dim sFileName As String = txtFilePath.Text.Substring(txtFilePath.Text.LastIndexOf("\"+ 1)
 
  byteSource = System.IO.File.ReadAllBytes(txtFilePath.Text)
  byteCompressed = oCCompression.CompressByte(byteSource)
 
  System.IO.File.WriteAllBytes(txtDestainationFolder.Text & "\" & sFileName & ".zip", byteCompressed)
 
  MsgBox("File compressed successfully and placed in destination folder", _
MsgBoxStyle.OkOnly, "Compression")
 
  Catch ex As Exception
  MsgBox("Compression failed. Reason: " & ex.ToString())
  End Try
 
End Sub

Description

txtFilePath.Text.Substring(txtFilePath.Text.LastIndexOf("\") + 1)  returns the file name which we use to assign name to the compressed file later. As I have mentioned before, filename or file extension do not have much importance in these compression. We can assign name as we desire.

·         byteSource = System.IO.File.ReadAllBytes(txtFilePath.Text) gets the byte array of the file.

·         byteCompressed = oCCompression.CompressByte(byteSource) gets the compressed byte array by using CompressByte() function.

·         System.IO.File.WriteAllBytes(txtDestainationFolder.Text & "\" & sFileName & ".zip", byteCompressed)  writes compressed byte array into <filename>.zip file. As I discussed before we can use any extension for the compressed file. But saving in .zip extension makes it to be decompressed by using WinZip software also.

Implement click event of  btnDecompress:

Listing 8 –Click event implementation of button btnDecompress

Private Sub btnDecompress_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) _
Handles btnDecompress.Click
 
  Dim oCDecompression As New CDecomp
  Dim byteDecompressed() As Byte
 
  ' Validate paths
  If IO.File.Exists(txtFilePath.Text) = False Then
    MsgBox("Please specify the valid file path to decompress", MsgBoxStyle.OkOnly)
    txtFilePath.Focus()
    Exit Sub
  Else
    If IO.Directory.Exists(txtDestainationFolder.Text) = False Then
      MsgBox("Please specify the valid path of destination folder", MsgBoxStyle.OkOnly)
      txtDestainationFolder.Focus()
      Exit Sub
    End If
  End If
 
 
  Try
  Dim sFileName As String = txtFilePath.Text.Substring(txtFilePath.Text.LastIndexOf("\") + 1)
  sFileName = sFileName.Remove(sFileName.LastIndexOf("."))
 
  byteDecompressed = oCDecompression.DecompressByte(System.IO.File.ReadAllBytes(txtFilePath.Text))
 
  System.IO.File.WriteAllBytes(txtDestainationFolder.Text & "\" & sFileName, byteDecompressed)
  MsgBox("File decompressed successfully and placed in destination folder", _
MsgBoxStyle.OkOnly, "Decompression")
 
  Catch ex As Exception
  MsgBox("Decompression failed. Reason: File used to decompress may not have gzip compression format")
  End Try
End Sub

Description

Dim sFileName As String = txtFilePath.Text.Substring(txtFilePath.Text.LastIndexOf("\") + 1) reads the filename to write into the decompressed byte.

·         sFileName = sFileName.Remove(sFileName.LastIndexOf(".")) removes the .zip extension.

·         byteDecompressed =  oCDecompression.DecompressByte(System.IO.File.ReadAllBytes( txtDestainationFolder.Text & "\" & sFileName & ".zip")) gets the decompressed byte array by using DecompressByte() function. This function takes the path of compressed file.

·         System.IO.File.WriteAllBytes(txtDestainationFolder.Text & "\" & sFileName, byteDecompressed) writes the decompressed byte array into file.

Build the application and run it. If run successfully then on the form windows specify the file to be compressed and folder location in the text box by using browse buttons given for that. Test the compression and decompression functionality of the application. You should get the output file in the destination folder which you set on the form. Verify the difference in file sizes of actual and compressed files. I will suggest to you to read the "Limitations of GZipStream and DeflateStream in Framework 2.0" section in this article before going to test application with different types and sizes of files to find ratio of compression.

In the above windows application example I have used byte array to byte array compression. In real life situations these functions are also useful when you need to apply compression with memory to memory data transfer over network where reading or writing files is not necessarily required. You might need to apply compression on xml format dataset collected from database at one end and to apply decompression at other end to get back the actual xml dataset. Here you can use functions CompressByte and DecompressByte defined above.

We can also implement byte array to memory stream compression by replacing CompressByte() with function CompressData() as defined in Listing 2 and/or replacing function DecompressByte() with DecompressData() as defined in Listing 4.


View Entire Article

User Comments

Title: soulpink   
Name: soul
Date: 2013-01-28 1:55:01 AM
Comment:
Mr. Singh, you have this kind of helping-hand and mind tutorial. It helps a lot. Thank you.
Title: soulpink   
Name: soul
Date: 2013-01-28 1:51:59 AM
Comment:
awesome. it helps a lot. thank you so much.excellent work guys..
Title: ghufran   
Name: kamal
Date: 2012-09-06 12:20:10 AM
Comment:
i have need for demo file and source code
Title: Thanks   
Name: masterkreatif.com
Date: 2012-06-16 10:08:54 AM
Comment:
Amazing, thanks a lot.. this is very usefu
Title: Re   
Name: rajanrufus
Date: 2011-12-27 8:03:35 PM
Comment:
Excellent post and informative. Thanks for your sharing.
Title: Gzip   
Name: Ron
Date: 2011-01-09 10:58:31 PM
Comment:
Can you help me with that problem?

how ca I compress database with a size of 1 gigabyte or more than.

thank you!
Title: Gzip   
Name: John Michael
Date: 2011-01-09 10:49:33 PM
Comment:
I think your code is Useless,
I tried it but it can not compress a large file such as database with a size of 1 Gigabyte or more than.
Title: lklkl   
Name: lkl
Date: 2011-01-02 8:29:17 AM
Comment:
not to bad
Title: Forgot something   
Name: Jake the snake
Date: 2010-11-12 3:49:28 PM
Comment:
Nice code, this is very useful. However, there is an error in your code. You are not assigning the values selected in the OpenFileDialog and FolderBrowserDialog to the text windows so when you select a file nothing shows up in the text box and same with the folder.

Code fails
Title: file compression/decompression in VC++ 2005   
Name: jay
Date: 2010-10-22 8:30:06 PM
Comment:
hello
i like your tuturial
i want your help in file compression
how i can write the file compression/decompression code in Visual C++ 2005
please help me
my email id jaydeep.baravkar@gmail.com
Title: Compressed (zipped) Folders Error   
Name: Rahul
Date: 2010-05-24 7:35:33 AM
Comment:
Hi, thx for such a nice article, i have implemented the code in my vb.net application and able to generate .zip file but unfortunately i couldn't ablr to open or extract content of zip file, it is throwing error as below :
The Compressed (zipped) Folder is invalid or corrupted.

Could you please help? (Rahul_Chitte@syntelinc.com)
Title: file compression/decompression in VC++ 2005   
Name: jay
Date: 2010-02-05 12:36:14 AM
Comment:
hello
i like your tuturial
i want your help in file compression
how i can write the file compression/decompression code in Visual C++ 2005
please help me
my email id jaydeep.baravkar@gmail.com
Title: file compression/decompression in VC++ 2005   
Name: jay
Date: 2010-02-03 1:35:12 PM
Comment:
hello
i like your tuturial
i want your help in file compression
how i can write the file compression/decompression code in Visual C++ 2005
please help me
Title: Decompressed files are huge   
Name: Raj
Date: 2009-12-10 11:17:57 AM
Comment:
Great tutorial Abhishek!
One problem that I am noticing is that when decompressing a file the file becomes almost 100 times the size that it should be. Any idea on where am I going wrong here ?
Regards,
-Raj
Title: Very Impressive   
Name: Paul Myers
Date: 2009-09-22 10:14:52 AM
Comment:
Thank you for this sample code. It is well written and very understandable.
Title: request   
Name: swarup saha
Date: 2009-06-30 12:49:22 PM
Comment:
dear bhaia,can i get C# code of image compression and decompression.if possible pls send me in this address:
swarup_04cse@yahoo.com
Title: Thank you   
Name: Mikael
Date: 2009-06-30 9:49:22 AM
Comment:
A thousand thanks, works perfect.
Title: Tanks man   
Name: Tim
Date: 2009-05-05 5:00:45 AM
Comment:
Hello, thank you for the tutorial, it was great, i love it.
i have som problem but i figure it out, so, now it works, and thanks agen...
Title: Training   
Name: Obama - USA President
Date: 2009-02-05 3:57:12 PM
Comment:
Great of you to share...yes we can.
Title: help me yaar as soon as   
Name: prince walia
Date: 2008-11-23 12:11:07 PM
Comment:
hello frnd,,,i m doing mca,,my sar give me aa project to cpmrss the files,,,but my project is nt complete,,plz send me the project oe help me,,
Title: Compression   
Name: Avaloan
Date: 2008-11-23 3:34:22 AM
Comment:
I think it's good but I don't see any compresses just a expand of file size.!
Title: Compression   
Name: Sree
Date: 2008-10-30 2:21:43 AM
Comment:
I have used the code in the script task in SQL Integration services. First it gives me an error at the step "objMemStream.Length" saying: disallows implicit conversion from Long to Int.
So i have tried type conversions.
It gets executed and a zip file is created but when i try to decompress it, it says it is bad or invalid file.
Can anybody help me on this?
Title: Compression   
Name: Stacy
Date: 2008-10-02 4:24:41 AM
Comment:
Hi,

I am working on an asp application and I have a string that needs to be passed from script file to asp page, but the string breaks coz of its large size.Can this function be used for the same.Also how do i convert string to byte.

Please reply soon
Title: compression   
Name: mike
Date: 2008-09-04 5:31:06 AM
Comment:
it can't comprees large file...65k is the limit..i hv tried compressing 90k file(TXT FILE)..bt to my surprise the compressed file is showg a larger memory thn its initial size..and there is no or a very little difference between gzip and deflate.am i doin any mistake here.?.plz help!!!
Title: compression   
Name: Jeevitha
Date: 2008-08-29 9:39:38 AM
Comment:
Nice Article. It's very useful to me. Thanks a lot.
Title: Compression and Decompression   
Name: Padma
Date: 2008-05-29 2:25:36 AM
Comment:
Article is very good....it helped me a lot...can u give article abt transferring an image file in vb6 using udp protocol....
mailid:belpadma@gmail.com
PH:080 22195854
Title: Senior Programmer/Analyst   
Name: Guillermo
Date: 2008-05-14 10:23:12 AM
Comment:
I am very thankful for this article because it helped me very very much...
Title: Senior Programmer/Analyst   
Name: J Eaves
Date: 2008-05-12 11:58:09 AM
Comment:
Great article and easy to follow. However, 2 issues. 1)I couldn't get code to work with CompressData() as MemoryStream. And 2)After I created a zip file and tried to open with WinZip 11, I get the following error "Cannot open file: it does not appear to be a valid archive."
Does anyone have thoughts or suggestions.
Thanks.
Title: Compression and Decompression of Files using Visual Basic 2005   
Name: Cammie McGinty
Date: 2008-01-27 3:04:27 PM
Comment:
Thank you for a clear and straightforward example.
Title: Reply to: Bloated results   
Name: Abhishek (Author)
Date: 2007-11-21 2:58:05 AM
Comment:
hi Jacob,
BTW which type of files you are trying to compress and decompress?
Are you using the byte counters properly if you are not decompressing entire compressed file at a time?
Title: Reply to: Give me idea   
Name: Abhishek (Author)
Date: 2007-11-21 2:55:50 AM
Comment:
Hi Netra,
sorry for late reply, i had stuck in some stuff.
You can achieve entire folder compression using DeflateStream but for this you have to implement your own logic to compress each file one by one inside the folder and then you can make a bundle of all compress files and also there should be a information file which should keep details of each file name, size etc which you can use while decompressing.
Frankly saying i have done this by myself but had some finding on this.
hope it helps you. If you got anyt idea on this please let me know. I will be thankful to you.
thanks.
Title: Bloated results   
Name: Jacob Kennedy
Date: 2007-11-02 5:29:13 PM
Comment:
I'm implementing your DecompressByte on a folder of files that were zipped using GZipStream, and it's working a lot better than what I had, but my decompressed files are ending up over a hundred times bigger than the original non-compressed files... any ideas?
Title: Give me idea   
Name: Netra
Date: 2007-10-22 5:26:55 AM
Comment:
Hi abhi,
i want to zip the folder containg files for eg. i have folder named ABC and in that folder i have 3 .txt files , i want to zip that ABC folder not only the files in that.
Can i done it at runtime , plz give me the idea. And i want to do it by using DeflateStream.
Title: Excellent idea....   
Name: Rajiv Tripathi
Date: 2007-07-05 3:40:00 PM
Comment:
Hi Abhi,
That's a really gr8 idea. Thx for sharing it with all of us.That has helped a lot. i hope you remember me by my name, I implemented your idea and it produced remarkable result.
thx & all the best!!
Title: rijovg@gmail.com   
Name: rijo
Date: 2007-06-28 6:23:07 AM
Comment:
i need an help would u plz contact on this id
Title: Re: File Extension   
Name: Abhishek Kumar Singh
Date: 2007-06-15 7:52:18 PM
Comment:
As the gzipstream and deflatestream are stream based classes, one way would be- you can add file exetension in byte() at first/last position before compression. Then read those bytes to get the file extenstion and remove those bytes before writing the file.
Usually you need to know the extension of file by any mean while writing decompressed file. If compressed byte() are being transferred using remote methods you can send file extension as extra parameter in the method.

Thanx.
Title: file extension   
Name: Theuns
Date: 2007-06-14 10:45:01 AM
Comment:
How do you keep the file extension when compressing it?
Title: My Feedback   
Name: Sunny Adeshara
Date: 2007-06-08 8:53:00 AM
Comment:
I am very thankful for this article because it helped me very much.
Title: Good Article Keep it up   
Name: Anjaiah Keesari
Date: 2007-05-24 9:05:54 AM
Comment:
Even I am working on Compression and Decompression with C# code your Article is very good. You Explained concepts very nice thanks keesari_anjaiah@yahoo.co.in
Title: I m proud of my best frined   
Name: Vinit Pratap Singh
Date: 2007-05-23 9:13:57 AM
Comment:
Hi... i don't know Visual Basic.. but i think its a very big implement by you.. i m very proud of u.. keep it up... with lots of new adventure.. . vinitpratap@gmail.com

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 9:45:44 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search