Compress and Decompress GZip RRS feed

  • Question

  • I've attached a routine that works if you are using a file system, but I'd like to convert the routine to using memorystream.  If anyone can help convert the italicized code to using a memory stream for compressing and decompressing to a GZIp instead of using a filestream/filesystem method I'd appreciate it.

       Public Sub OpenFile(ByVal FileId As String, Optional ByVal PreviewOnly As Boolean = False)
            'get the file data
            Dim oTable As DataTable = Nothing
            Dim command As System.Data.OleDb.OleDbCommand
            Dim oCon As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(GetConnectionString)
            Dim buffer As Byte()
            Dim oFileStream As System.IO.FileStream
            Dim writer As BinaryWriter
            Dim bufferSize As Integer = 100
            ' The BLOB byte() buffer to be filled by GetBytes.
            Dim outByte(bufferSize - 1) As Byte
            Dim FinaloutByte() As Byte
            ' The bytes returned from GetBytes.
            Dim retval As Long
            ' The starting position in the BLOB output.
            Dim startIndex As Long = 0
            Dim strFileDesc As String = ""
            Dim strSeqNum As Integer = 0
            Dim strRecordId As String = ""
            Dim bAdminViewOnly As Boolean = False
                'get image data from database
                 command = New System.Data.OleDb.OleDbCommand("Select FileName, FilePath, Linked, FileData, FileDesc, SeqNum, RecordId, AdminViewOnly FROM Files WHERE FileId = '" & FileId & "'", oCon)
                'convert image data from db field to byte array
                Dim reader As OleDb.OleDbDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess)
                If reader.HasRows AndAlso reader.Read() Then
                    Dim strFileName As String = reader.GetString(0)
                    Dim strFilePath As String
                    Dim NewFileName As String
                        strFilePath = reader.GetString(1)
                        If UCase(Strings.Right(strFilePath, 1)) = "\" Then
                            strFilePath = strFilePath & strFileName
                        End If
                    Catch ex As Exception
                        strFilePath = TempFileDirectory & strFileName
                    End Try
                    Dim blnLinked As Boolean = reader.GetBoolean(2)
                    If Not blnLinked Then
                        If Not System.IO.Directory.Exists(TempFileDirectory) Then
                        End If
                        If UCase(Strings.Right(strFilePath, 3)) = ".GZ" OrElse UCase(Strings.Right(strFilePath & strFileName, 3)) = ".GZ" Then
                            Dim oFileInfo As New FileInfo(strFilePath)
                            Dim fileToDecompress As FileInfo
                            fileToDecompress = oFileInfo
                            Dim newFilePath As String
                            Dim newFileStream As FileStream
                            Dim cNewFileStream As FileStream
                            Using originalFileStream As FileStream = fileToDecompress.OpenRead()
                                Dim currentFileName As String = fileToDecompress.FullName
                                newFilePath = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length)
                                NewFileName = Strings.Right(newFilePath, newFilePath.Length - InStrRev(newFilePath, "\"))
                                Using decompressedFileStream As FileStream = File.Create(newFilePath)
                                    Using decompressionStream As GZipStream = New GZipStream(originalFileStream, CompressionMode.Decompress)
                                        newFileStream = decompressedFileStream
                                     End Using
                                End Using
                            End Using
                            cNewFileStream = newFileStream
                            ShellFile(newFileStream.Name, True)
                            Dim cFileInfo As New FileInfo(newFilePath)
                            Dim fileToCompress As FileInfo
                            fileToCompress = cFileInfo
                            Dim nFilePath As String
                            Dim nFileName As String
                            Dim nPath As String
                            Using coriginalFileStream As FileStream = fileToCompress.OpenRead()
                                If (File.GetAttributes(fileToCompress.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And fileToCompress.Extension <> ".gz" Then
                                    Using compressedFileStream As FileStream = File.Create(fileToCompress.FullName & ".gz")
                                        Using compressionStream As GZipStream = New GZipStream(compressedFileStream, CompressionMode.Compress)
                                            nFilePath = compressedFileStream.Name
                                            nFileName = Strings.Right(nFilePath, nFilePath.Length - InStrRev(nFilePath, "\"))
                                        End Using
                                    End Using
                                End If
                            End Using
                            Dim justPath As String
                            oFileInfo = Nothing
                            cFileInfo = Nothing
                            justPath = nFilePath.Replace(nFileName, "")
                            FileCopy(nFilePath, TempFileDirectory & nFileName)
                            strFileDesc = reader.GetString(4)
                            strSeqNum = reader.GetInt16(5)
                            strRecordId = reader.GetGuid(6).ToString
                            bAdminViewOnly = reader.GetBoolean(7)
                            Dim fileUpdate As Date
                            fileUpdate = Date.Today
                            UpdateFile(FileId, justPath, strFileDesc, blnLinked, strRecordId, nFileName, strSeqNum, bAdminViewOnly, fileUpdate)
                            oFileStream = New System.IO.FileStream(TempFileDirectory & strFileName, IO.FileMode.OpenOrCreate, FileAccess.Write)
                            writer = New BinaryWriter(oFileStream)
                            ' Reset the starting byte for a new BLOB.
                            startIndex = 0
                            ' Read bytes into outByte() and retain the number of bytes returned.
                            retval = reader.GetBytes(3, startIndex, outByte, 0, bufferSize)
                            ' Continue while there are bytes beyond the size of the buffer.
                            Do While retval = bufferSize
                                ' Reposition start index to end of the last buffer and fill buffer.
                                retval = reader.GetBytes(3, startIndex, outByte, 0, bufferSize)
                                If retval < 100 AndAlso retval > 0 Then
                                    ReDim FinaloutByte(retval - 1)
                                    retval = reader.GetBytes(3, startIndex, FinaloutByte, 0, retval)
                                End If
                            ' Write the remaining buffer.
                            If retval > 0 Then
                                writer.Write(FinaloutByte) ', 0, retval)
                            End If
                            strFileDesc = reader.GetString(4)
                            strSeqNum = reader.GetInt16(5)
                            strRecordId = reader.GetGuid(6).ToString
                            bAdminViewOnly = reader.GetBoolean(7)
                            ' Close the output file.
                            ShellFile(TempFileDirectory & strFileName, bAsync:=Not PreviewOnly)
                        End If
                        If System.IO.File.Exists(strFilePath & strFileName) Then
                            ShellFile(strFilePath & strFileName, bAsync:=Not PreviewOnly)
                        End If
                    End If
                    If System.IO.File.Exists(oTable.Rows(0).Item("FilePath").ToString & oTable.Rows(0).Item("FileName")) Then
                        ShellFile(oTable.Rows(0).Item("FilePath") & oTable.Rows(0).Item("FileName"))
                        MessageBox.Show("The file does not exist, please remove the file", "File Not Found", MessageBoxButtons.OK)
                    End If
                End If
            Catch ex As Exception
                HandleError(ex, "modCodepal", "OpenFile")
                oFileStream = Nothing
                If Not oTable Is Nothing Then oTable.Dispose()
                If Not oCon Is Nothing Then
                    If oCon.State = ConnectionState.Open Then
                    End If
                End If
            End Try
        End Sub

    Wednesday, November 13, 2019 9:25 PM

All replies

  • Hi,

    This is a simple example of compressing and decompressing using a memory stream. I hope this helps you.

    Imports System.IO
    Imports System.IO.Compression
    Imports System.Text
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim result As String, myString As String = "testCompress"
            Dim outFile As MemoryStream = New MemoryStream()
            outFile = Compress(Encoding.UTF8.GetBytes(myString))
            result = Encoding.UTF8.GetString(Decompress(outFile))
        End Sub
        Public Shared Function Compress(ByVal inBytes As Byte()) As MemoryStream
            Dim outStream As MemoryStream = New MemoryStream()
            Using intStream As MemoryStream = New MemoryStream(inBytes)
                Using testCompress As GZipStream = New GZipStream(outStream, CompressionMode.Compress)
                End Using
            End Using
            Return outStream
        End Function
        Public Shared Function Decompress(ByVal inStream As MemoryStream) As Byte()
            Dim result As Byte() = Nothing
            Dim compressedStream As MemoryStream = New MemoryStream(inStream.ToArray())
            Using outStream As MemoryStream = New MemoryStream()
                Using testDecompress As GZipStream = New GZipStream(compressedStream, CompressionMode.Decompress)
                    result = outStream.ToArray()
                End Using
            End Using
            Return result
        End Function
    End Class

    Best Regards,


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Thursday, November 14, 2019 4:48 AM