0

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

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
chocano14
  • 13
  • 2
  • 1
    I'm confused why you're using ASCII at all. Just take the bytes from the zip file and convert them to base64. Convert them back the same way, as in [Decode base64 to image in vb.net](https://stackoverflow.com/q/49507221/215552) – Heretic Monkey Dec 14 '22 at 21:43
  • 1
    Don't call `.Dispose()` for an item that was already created in a `Using` block. Ensuring Dispose() is always called for you at the appropriate time is the whole point of the Using block in the first place. – Joel Coehoorn Dec 14 '22 at 22:00

1 Answers1

3

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")
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794