Friday, September 26, 2008

Unzipping a zip file with subfolder with SharpZipLib and VB.net

Unzipping routine using ICSharpCode (IC#Code) released open source dll, called SharpZipLib (#ZipLib), downloadable here


Imports ICSharpCode.SharpZipLib.Zip
......
If File.Exists(fileName) Then

    destPath = fileName.Substring(0, fileName.Length - 4)

    If Not Directory.Exists(destPath) Then
        Directory.CreateDirectory(destPath)
    Else
        For Each s As String In Directory.GetFiles(destPath)
            File.Delete(s)
        Next
    End If

    Dim inStream As New ZipInputStream(File.OpenRead(fileName))
    Dim outStream As FileStream
    Dim entry As ZipEntry
    Dim buff(2047) As Byte
    Dim bytes As Integer

    Do While True
        Try
            entry = inStream.GetNextEntry()
            If entry Is Nothing Then
                Exit Do
            End If

            If entry.Name.Last() = "/" Then
                Directory.CreateDirectory(destPath & "\" & _
                entry.Name.Replace("/", "\"))
            Else
                Try
                    outStream = File.Create(destPath & _
                    "\" & entry.Name, 2048)
                    Do While True
                        bytes = inStream.Read(buff, 0, 2048)
                        If bytes = 0 Then
                            Exit Do
                        End If
                        outStream.Write(buff, 0, bytes)
                    Loop
                    outStream.Close()
                Catch
                End Try
            End If
        Catch
ex As ZipException
            rtn += ex.Message & vbCrLf
        End Try
    Loop

    inStream.Close()
Else
    rtn = "File '" & fileName & "' not found."
End If

No comments: