Unzipping a File in vb.net

Spartin503 picture Spartin503 · Aug 13, 2013 · Viewed 8.2k times · Source

I have an embedded resource in my .exe that is a zip file, I would like to move it out of the resources and unzip it to a specific folder.

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btn_Install.Click
    Dim Dir_File As String = "C:\FTB"
    Dim Dir_Temp As String = "C:\Temp\Unleashed.zip"

    System.IO.File.WriteAllBytes(Dir_Temp, My.Resources.Unleashed)

    Dim directorySelected As DirectoryInfo = New DirectoryInfo(Dir_Temp)

End Sub

But I have no way of extracting the the .zip file to a directory. So all I need now is a way to actual extract the .zip.

I tried this:

Dim directorySelected As DirectoryInfo = New DirectoryInfo(Dir_Temp)
    For Each fileToDecompress As FileInfo In directorySelected.GetFiles("Unleashed.zip")
        Using OriginalFileStream As FileStream = fileToDecompress.OpenRead()
            Using decompressedFileStream As FileStream = File.Create(Dir_File & "\Unleashed")
                Using decompressionStream As GZipStream = New GZipStream(OriginalFileStream, CompressionMode.Decompress)
                    decompressionStream.CopyTo(decompressedFileStream)
                End Using
            End Using
        End Using
    Next

But all that did was give me an error about a magic number. Any help is very much appreciated.

Answer

Heslacher picture Heslacher · Aug 13, 2013

Your problem is allready discussed here: https://stackoverflow.com/a/11273427/2655508

The GZipStream class is not suitable to read compressed archives in the .gz or .zip format. It only knows how to de/compress data, it doesn't know anything about the archive file structure. Which can contain multiple files, note how the class doesn't have any way to select the specific file in the archive you want to decompress.

The solution is to use NET 4.5 which contains inside the System.IO.Compression namespace the needed classes with their methods for creating, manipulating and extracting items in/out of a zip file.

See e.g. System.IO.Compression.ZipFileExtensions.ExtractToDirectory()