Home > Blockchain >  How to decode zip file and save it in vb.net?
How to decode zip file and save it in vb.net?

Time:12-20

I am creating a project where a zip file is base 64 encoded and then the file is decoded and saved, but when I unzip the file it gives a corrupted file error.

Dim zip As New Xs_UnZipFilesCompat
''Encode()
Dim base64encoded As String
Using r As StreamReader = New StreamReader(File.OpenRead("E:\zip_test.zip"))
    Dim data As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd())
    base64encoded = System.Convert.ToBase64String(data)
    r.Dispose()
End Using

'decode --> write back
Using w As StreamWriter = New StreamWriter(File.Create("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip"))
    Dim data As Byte() = System.Convert.FromBase64String(base64encoded)
    w.Write(System.Text.ASCIIEncoding.ASCII.GetString(data))
    w.Dispose()
End Using

I can't find the solution

CodePudding user response:

The encode is not correct. Specifically, this line:

Dim data As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd())

You definitely don't want to read a file with a *.zip extension as if it were made of ASCII characters. Replace it with this:

Dim data As Byte() = System.IO.File.ReadAllBytes(fileName)

Which means you also no longer need the StreamReader, so we end up with this:

Public Function Encode(fileName As String) As String
    Return Convert.ToBase64String(IO.File.ReadAllBytes(fileName))
End Function

Then the Decode would look like this:

Public Sub Decode(fileName As String, base64Data As String)
    IO.File.WriteAllBytes(fileName, Convert.FromBase64String(base64Data))
End Sub

And you could call them like this:

Dim base64encoded As String = Encode("E:\zip_test.zip")
Decode("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip", base64encoded)

Or we can write it without the methods like this:

Dim base64encoded As String = Convert.ToBase64String(IO.File.ReadAllBytes("E:\zip_test.zip"))
IO.File.WriteAllBytes("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip", Convert.FromBase64String(base64encoded))

But it seems like that all reduces down to this:

IO.File.Copy("E:\zip_test.zip", "e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip")
  • Related