How to create compressed files

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
9 posts Page 1 of 1
Contributors
User avatar
BlakPilar
New Member
New Member
Posts: 15
Joined: Fri Apr 08, 2011 7:49 pm

How to create compressed files
BlakPilar
Have you ever wanted to create compressed files in Visual Basic .NET? I'm sure you have. Well, this here tutorial of mine will teach you how!

First, you need to know something. This will NOT create .zip files and does not support .zip (or .rar for that matter) files. It only supports .gz (GZip) files. Though they are both compression files, their structures differ and therefore are not the same thing. Also, this will ONLY work with the .NET Framework 4 (aka VB 2010).

Now that we have that out of the way, let's get started. Start up a new project, or add a new form or whatever suits your fancy, and add the following items to the form:
  • 2 TextBoxes (One for the file and one for the output directory; I named them txtFile and txtOutDir, respectively)
  • 4 Buttons (Two with texts of "..." for searching, and two for compressing and decompressing. See note.)
  • 1 FolderBrowserDialog (Named dlgDirectory)
  • 1 OpenFileDialog (Named dlgFile)
Note: One of the buttons with the "..." text must be named btnFileBrowse (place it next to txtFile), and the other must be named btnOutBrowse (place it next to txtOutDir). The other two buttons are for compressing and decompressing, and must be named btnCompress and btnDecompress respectively.

Here is what my form looks like:
Image

For the code (to view it, right click somewhere on the form and click "View Code"), you're going to want to import these, or else you'll be doing more typing than neccessary.
Code: Select all
Imports System
Imports System.IO
Imports System.IO.Compression
Now, after importing these, right under Public Class _form-name_, declare these two variables:
Code: Select all
Private currentFile As String
Private outDirectory As String
Those two variables will keep track of the selected file's path, and the output directory for the file.

After that, methinks we should setup our two subs for compressing and decompressing; you know, get them out of the way. Well, here they are (I have comments on them, so you should be able to get the jist of what they're doing):
Code: Select all
Private Sub Compress(ByVal fi As FileInfo, ByRef directory As String)
        Using inFile As FileStream = fi.OpenRead()                                  'Create a stream of the source file.
            If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) _
                <> FileAttributes.Hidden And fi.Extension <> ".gz" Then             'If the file is not hidden or already compressed
                Using outFile As FileStream = File.Create(directory & fi.Name _
                                                          & ".gz")                  'Create stream of new .gz file      
                    Using GZipFile As GZipStream = _
                     New GZipStream(outFile, CompressionMode.Compress)              'Create GZip stream of new file
                        inFile.CopyTo(GZipFile)                                     'Copy the selected file into the compression stream
                        GZipFile.Close()                                            'Close GZip stream
                        outFile.Close()                                             'Close file stream
                        inFile.Close()                                              'Close main stream
                    End Using
                End Using
            End If
        End Using
 End Sub

 Private Sub Decompress(ByVal fi As FileInfo, ByRef directory As String)
        If fi.Extension = ".gz" Then                                                'Only if the file is a GZip file
            Using inFile As FileStream = fi.OpenRead()                              'Create a stream of the compressed file
                Dim curFile As String = fi.Name
                Dim origName As String = Mid(curFile, 1, Len(curFile) - 3)
                ' Create the decompressed file.
                Using outFile As FileStream = File.Create(directory & origName)     'Create a new file stream from original file
                    Using GZipFile As GZipStream = New GZipStream(inFile, _
                     CompressionMode.Decompress)                                    'Create a new decompression stream
                        GZipFile.CopyTo(outFile)                                    'Copy the decompression stream into the output file
                        GZipFile.Close()                                            'Close the GZip stream
                        outFile.Close()                                             'Close the file stream
                        inFile.Close()                                              'Close the main stream
                    End Using
                End Using
            End Using
        Else
            Throw New Exception("File is not in the GZip format.")
        End If
 End Sub
Now, this little bit that I'm about to tell you is completely optional. I just use things like this as a sort of... tidying up of my programs.
Code: Select all
Private Sub ClearEntries()
        currentFile = ""
        outDirectory = ""
        txtFile.Text = ""
        txtOutDir.Text = ""
        txtFile.Select()
End Sub
Here's the rest of the code, which just sets up our file and output directory browsing, as well as our Compress and Decompress button clicking:
Code: Select all
Private Sub BrowseFile() Handles btnFileBrowse.Click
        If dlgFile.ShowDialog = DialogResult.OK Then                                'If and only if the user selected OK,
            currentFile = dlgFile.FileName                                          'Get the selected file
            txtFile.Text = dlgFile.SafeFileName                                     'Display the filename only (minus directories)
        End If
 End Sub

 Private Sub BrowseOutputDirectory() Handles btnOutBrowse.Click
        If dlgDirectory.ShowDialog = DialogResult.OK Then                           'If and only if the user clicks OK,
            outDirectory = dlgDirectory.SelectedPath & "\"                          'Get the selected path (plus the needed "\")
            txtOutDir.Text = outDirectory                                           'Display the output directory
        End If
 End Sub

 Private Sub btnCompress_Click() Handles btnCompress.Click
        If txtFile.Text = "" Then                                                   'If no file has been selected,
            MessageBox.Show("Please select a file to be compressed.", "Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)             'Display error
        ElseIf txtOutDir.Text = "" Then                                             'If no output directory,
            MessageBox.Show("Please select an output directory for the file.", _
                            "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)    'Display error
        Else                                                                        'Otherwise, if everything is in order,
            Try
                Call Compress(New FileInfo(currentFile), outDirectory)              'Call the sub to compress selected file
                MessageBox.Show("File " & currentFile & vbLf & _
                                "has been compressed and placed into: " & _
                                vbLf & outDirectory, "Success")                     'Tell of success
                Call ClearEntries()                                                 'Tidy up
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
 End Sub

 Private Sub btnDecompress_Click() Handles btnDecompress.Click
        If txtFile.Text = "" Then                                                   'If no file selected
            MessageBox.Show("Please select a file to be decompressed.", "Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)             'Display error
        ElseIf txtOutDir.Text = "" Then                                             'If no output directory,
            MessageBox.Show("Please select an output directory for the file.", _
                            "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)    'Display error
        Else                                                                        'Otherwise, if both arguments have been provided,
            Try
                Call Decompress(New FileInfo(currentFile), outDirectory)            'Call the sub to decompress the file
                MessageBox.Show("File " & currentFile & vbLf & _
                                "has been decompressed and placed into:" & _
                                vbLf & outDirectory, "Success")                     'Tell of success
                Call ClearEntries()                                                 'Tidy up
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
End Sub
Well folks, that's all you need to do to compress files! I'll be tweaking this to see if I can compress entire directories, unless someone else beats me... ;) I hope you learned something!

P.S. - If someone goes and makes a video on YouTube on how to do this, please just say that you learned it from me. That's all I ask.
You do not have the required permissions to view the files attached to this post.
Last edited by BlakPilar on Tue Apr 12, 2011 9:55 pm, edited 3 times in total.
Image
User avatar
Napster1488
VIP - Donator
VIP - Donator
Posts: 524
Joined: Fri Jan 07, 2011 8:41 pm

Re: Create compressed files
Napster1488
Cool Thanks!
it creates a ZIP File ?!
YouTube Downloader v3.0
Image
Image
Image
User avatar
BlakPilar
New Member
New Member
Posts: 15
Joined: Fri Apr 08, 2011 7:49 pm

Re: Create compressed files
BlakPilar
First, you need to know something. This will NOT create .zip files and does not support .zip (or .rar for that matter) files. It only supports .gz (GZip) files. Though they are both compression files, their structures differ and therefore are not the same thing. Also, this will ONLY work with the .NET Framework 4 (aka VB 2010).
Image
User avatar
Jg99
VIP - Site Partner
VIP - Site Partner
Posts: 453
Joined: Sun Mar 20, 2011 5:04 am

Re: How to create compressed files
Jg99
Awesome! I might use this for my Zip utility for JAmes OS
http://www.sctechusa.com SilverCloud Website
User avatar
Bogoh67
VIP - Site Partner
VIP - Site Partner
Posts: 656
Joined: Sun Apr 18, 2010 8:20 pm

Re: How to create compressed files
Bogoh67
not true i have seen a tutorial on how to create a .zip file on leetcoders.org
User avatar
BlakPilar
New Member
New Member
Posts: 15
Joined: Fri Apr 08, 2011 7:49 pm

not true i have seen a tutorial on how to create a .zip file on leetcoders.org
It was probably using some kind of non-VB library/reference like DotNetZip (if not, then it more than likely did not use this (System.IO.Compression) method). Visual Studio itself has no direct support for .zip files, only .gz. You can feel free to prove me wrong, but I'm 99% confident in my previous statements.
Image
GoodGuy17
Coding God
Coding God
Posts: 1610
Joined: Mon Sep 07, 2009 12:25 am

Does your code in the tutorial catch the exception if you try to compress a directory which contains directories? If not, you should add it.

Otherwise, looks like a good tutorial. cooll;
User avatar
BlakPilar
New Member
New Member
Posts: 15
Joined: Fri Apr 08, 2011 7:49 pm

Does your code in the tutorial catch the exception if you try to compress a directory which contains directories?
Well, this tutorial is for single files only (if you look, you'll see I use an OpenFileDialog), but I'm working on the directory compression right now and I'm going to try to include any and all sub-directories, as well as their files, instead of just the files in the parent directory.
Image
User avatar
RonaldHarvey
Top Poster
Top Poster
Posts: 113
Joined: Tue Apr 05, 2011 2:32 pm

Good tutorial for future apps. Thanks cooll;
9 posts Page 1 of 1
Return to “Tutorials”