jonhopkins jonhopkins - 11 months ago 54 Question

VB.Net how to read a compressed text file directly into an array of strings

Is it possible to read a zipped text file like a normal text file without having to extract it first, and if so, how? Currently, I have to extract the file, read all the lines to an array of strings, and then delete the extracted file.

Dim arrLines() As String
arrLines = IO.File.ReadAllLines(Application.StartupPath & "\" & filename)
Dim FSO = CreateObject("Scripting.FileSystemObject")
FSO.DeleteFile(Application.StartupPath & "\" & filename)
Catch ex As Exception
Return False
End Try
'do stuff with arrLines...

I would prefer not to need to do this. If someone could tell me how to do something like
WITHOUT using third-party libraries, I would really appreciate it.

Answer Source

You can achieve this by:

  1. Add references of System.IO.Comression and System.IO.Compression.FileSystem
  2. Add Imports of System.IO.Compression

You can then use the following code to read the content to a file and store it to a string variable. In this particular example, I have the compressed file name "File1.txt" stored in a textbox on the main form (tbFile) and I have the contents of the compressed file displayed in a textbox (tb1) on the main form.

Private Sub bRead_Click(sender As Object, e As EventArgs) Handles bRead.Click
        Using archive As ZipArchive = Compression.ZipFile.Open(zipDest, ZipArchiveMode.Read)
            Dim entry As ZipArchiveEntry = archive.GetEntry(tbFile.Text)
            Dim s As String = ""
            Using sr As StreamReader = New StreamReader(entry.Open())
                s = sr.ReadToEnd()
            End Using
            tb1.Text = s
        End Using
    Catch ex As Exception
    End Try
End Sub