Zip/Unzip files from your VB.NET application

In order to add zip/unzip functionality to your programs you don't have to use third party components and libraries. .NET Framework has all you need via J#. Below you will find a translation of source code to Vb.NET from C#, found at codeproject.com posted by Valeri.

'To unzip Call
Try
Ziplib.Uncompress("C:\Testing.zip", "C:\")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

'To Zip Call
Dim s(1) As String
Try
s(0) = "C:\ZipTest\test.txt"
s(1) = "C:\ZipTest\test.doc"

Ziplib.Compress(s, "C:\Testing.zip")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Imports java.util.zip
Imports java.io

Public Class Ziplib

Public Shared Function Uncompress(ByVal strZipFileName As String, ByVal strLocation As String) As Boolean
Try
Dim oFileInputStream As New java.io.FileInputStream(strZipFileName)
Dim oZipInputStream As New java.util.zip.ZipInputStream(oFileInputStream)
Dim bTrue As Boolean = True
Dim sbBuf(1024) As SByte

While 1 = 1
Dim oZipEntry As ZipEntry = oZipInputStream.getNextEntry()

If oZipEntry Is Nothing Then Exit While

If oZipEntry.isDirectory Then
If Not My.Computer.FileSystem.DirectoryExists(strLocation & oZipEntry.getName) Then
My.Computer.FileSystem.CreateDirectory(strLocation & oZipEntry.getName)
End If
Else


Dim oFileOutputStream As New java.io.FileOutputStream(strLocation.Replace("\", "/") & oZipEntry.getName())

While 1 = 1
Dim iLen As Integer = oZipInputStream.read(sbBuf)
If iLen < 0 Then Exit While
oFileOutputStream.write(sbBuf, 0, iLen)
End While
oFileOutputStream.close()
End If
End While
oZipInputStream.close()
oFileInputStream.close()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function

Public Shared Function Compress(ByVal strFileNames() As String, ByVal strZipFileName As String) As Boolean
Try
Compress = False
Dim oFileOutputStream As New java.io.FileOutputStream(strZipFileName)
Dim oZipOutputStream As New java.util.zip.ZipOutputStream(oFileOutputStream)

For Each strFileName As String In strFileNames
Dim oFileInputStream As New java.io.FileInputStream(strFileName)
Dim oZipEntry As New java.util.zip.ZipEntry(strFileName.Substring(3).Replace("\", "/"))

oZipOutputStream.putNextEntry(oZipEntry)
Dim sbBuf(1024) As SByte
While 1 = 1
Dim iLen As Integer = oFileInputStream.read(sbBuf)
If iLen < 0 Then Exit While
oZipOutputStream.write(sbBuf, 0, iLen)
End While
oZipOutputStream.closeEntry()
oFileInputStream.close()
Next

oZipOutputStream.close()
oFileOutputStream.close()

Return True

Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
End Class



Search from any Web page with powerful protection. Get the FREE Windows Live Toolbar Today!
Try it now!

No comments: