0

I have a program that compresses a file using BZip2 then saves it to a new file.

Public Sub Create(ByVal outPathname As String, ByVal filePath As String)
    Dim msCompressed As New MemoryStream()
    Dim zosCompressed As New BZip2OutputStream(msCompressed)
    Dim fileInput As New FileStream(filePath, FileMode.Open)
    Dim buffer As Byte() = GetStreamAsByteArray(fileInput)
    zosCompressed.Write(buffer, 0, buffer.Length)
    zosCompressed.Flush()
    zosCompressed.Close()
    buffer = msCompressed.ToArray()
    Dim FileOutput As New FileStream(outPathname, FileMode.Create, FileAccess.Write)
    FileOutput.Write(buffer, 0, buffer.LongLength)
    FileOutput.Flush()
    FileOutput.Close()
End Sub

But I can't seem to figure out why I can't decompress the file it created. Can somebody tell me what's wrong with my decompressor here? (It's in a separate program than the compressor.)

Public Sub Extract(ByVal archiveFilenameIn As String, ByVal outFolder As String)
    Dim fileInput As New FileStream(archiveFilenameIn, FileMode.Open)
    Dim msUncompressed As New MemoryStream(GetStreamAsByteArray(fileInput))
    Dim zosDecompressed As New BZip2InputStream(msUncompressed)
    Dim buffer As Byte() = GetStreamAsByteArray(fileInput)
    zosDecompressed.Read(buffer, 0, buffer.Length())
    buffer = msUncompressed.ToArray()
    Dim FileOutput As New FileStream(outFolder & "\temporary.bmp", FileMode.Create, FileAccess.Write)
    FileOutput.Write(buffer, 0, buffer.LongLength)
    FileOutput.Flush()
    FileOutput.Close()
    zosDecompressed.Close()
    msUncompressed.Close()
    fileInput.Close()
End Sub

EDIT: I'm also using a function for converting a stream to a byte array here:

Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
    Dim streamLength As Integer = Convert.ToInt32(stream.Length)
    Dim fileData As Byte() = New Byte(streamLength) {}

    ' Read the file into a byte array
    stream.Read(fileData, 0, streamLength)
    stream.Close()

    Return fileData
End Function

Help?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Garrett Outlaw
  • 215
  • 3
  • 6
  • 16

1 Answers1

0

Try to Finalize BZip2OutputStream before using written data. That was helpfull for me.

zosCompressed.Finalize();
buffer = msCompressed.ToArray();

BZip2OutputStream usage example.

Victor
  • 1
  • The usefulness of this is limited, as calling `Finalize()` closes the underlying memory stream and totally defeats the purpose of having a compressed memory stream. – ajeh May 17 '16 at 20:37