Tuesday, September 30, 2008

Zipping and Unzipping Files Using Vb.Net

Set a Reference to the Following .Net Component:
vjslib

Classes to Import:


Imports System.IO
Imports java.io
Imports java.util
Imports java.util.zip
Imports System.Collections.Generic

To Zip the Files:

Public Sub Zip(ByVal zipFileName As String, ByVal sourceFiles As List(Of String))
' Create an output zip file.
Dim filOpStrm As New FileOutputStream(zipFileName, False)
Dim zipOpStrm As New ZipOutputStream(filOpStrm)

' Add the files by reading from the input file, and writing through the
' Zip compression routines.
For Each strFilName As String In sourceFiles
Dim filIpStrm As New FileInputStream(strFilName)
Dim ze As New ZipEntry(Path.GetFileName(strFilName))

zipOpStrm.putNextEntry(ze)

Dim buffer As SByte() = New SByte(1023) {}

Dim len As Integer = 0

' Continue to write the buffer until the end of the data.
While len >= 0
len = filIpStrm.read(buffer)
If len >= 0 Then
zipOpStrm.write(buffer, 0, len)
End If
End While

filIpStrm.close()
Next

' Close the streams.
zipOpStrm.closeEntry()
zipOpStrm.close()
filOpStrm.close()
End Sub

To UnZip the Files:

Private Shared Function GetZipFiles(ByVal zipfil As ZipFile) As List(Of ZipEntry)
Dim lstZip As New List(Of ZipEntry)()
Dim zipEnum As Enumeration = zipfil.entries()
While zipEnum.hasMoreElements()
Dim zip As ZipEntry = DirectCast(zipEnum.nextElement(), ZipEntry)
lstZip.Add(zip)
End While

Return lstZip
End Function

Public Shared Sub Unzip(ByVal zipFileName As String, ByVal destinationPath As String)
Dim zipfile As New ZipFile(zipFileName)
Dim zipFileList As List(Of ZipEntry) = GetZipFiles(zipfile)

For Each file As ZipEntry In zipFileList
If Not file.isDirectory() Then
Dim s As InputStream = zipfile.getInputStream(file)
Try
Dim fileName As String = file.getName()
Dim directoryName As String = Path.Combine(destinationPath, Path.GetDirectoryName(fileName))

If Not Directory.Exists(directoryName) Then
Directory.CreateDirectory(directoryName)
End If
Dim outputName As String = Path.Combine(directoryName, Path.GetFileName(fileName))
Dim dest As New FileOutputStream(outputName)
Try
Dim len As Integer = 0
Dim buffer As SByte() = New SByte(7167) {}
While len >= 0
len = s.read(buffer)
If len >= 0 Then
dest.write(buffer, 0, len)
End If
End While
Finally
dest.close()
End Try
Finally

s.close()
End Try
End If
Next
End Sub

Tuesday, September 2, 2008

Welcome

Hi Friends,

Welcome to my blog. Here you will find many ways to deal with your problems on Vb.Net 2005 and making the most of the tools available in the package. This blog will contain self tested codes and information gathered from different websites and verified by me. This blog will help all those budding developers like me to go beyond their scope and make the most of their brain.

Hoping to help you all get what you want.

Regards
Mohit Agarwal