The code below shows how you could compress a file.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' get the file name
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
Dim FileName = OpenFileDialog1.FileName
Try
' create the zip archive
Dim Z As System.IO.Packaging.ZipPackage
Z = System.IO.Packaging.Package.Open(FileName & ".zip", IO.FileMode.Create)
' read all the bytes of the file
Dim B = System.IO.File.ReadAllBytes(FileName)
' create a uri for the file
Dim partUriDocument As Uri = System.IO.Packaging.PackUriHelper.CreatePartUri(New Uri(System.IO.Path.GetFileName(FileName), UriKind.Relative))
' create a part
Dim P = Z.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Application.Zip, IO.Packaging.CompressionOption.Maximum)
' write the content into the part
P.GetStream.Write(B, 0, B.Length)
' close the zip file
Z.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
As for decompression, this is a small code that does so:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' get the file name
Dim OFD As New OpenFileDialog
If OFD.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
Dim FileName = OFD.FileName
' get the save location
Dim FBD As New FolderBrowserDialog
If FBD.ShowDialog = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
Try
' open the zip archive
Dim Z As System.IO.Packaging.ZipPackage
Z = System.IO.Packaging.Package.Open(FileName, IO.FileMode.Open)
' loop on every part/file
For Each P As System.IO.Packaging.PackagePart In Z.GetParts
' get the file name
Dim FN As String = FBD.SelectedPath & P.Uri.OriginalString
' open the steams
Dim S = P.GetStream(System.IO.FileMode.Open)
Dim S2 As New System.IO.FileStream(FN, IO.FileMode.Create)
' use buffer of 1KB , you could use more
Dim Buffer(0 To 1023) As Byte
Do
' read from the stream
Dim R = S.Read(Buffer, 0, Buffer.Length)
' if a byte or more was read, then write it, else stop the loop
If R <> 0 Then
S2.Write(Buffer, 0, R)
Else
Exit Do
End If
Loop
' close both files
S.Close()
S2.Close()
Next
' close the zip file
Z.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub