Utiliser la compression GZip en Dotnet

dotnet-gzip

Voila une petite classe qui permet de compresser et décompresser en utilisant un stream GZIP:

Imports System.IO
Imports System.IO.Compression
Imports System.Text

Public Class GZipper

    'Fonction qui zip une chaine de caractères
    Public Shared Function Zip(ByVal value As String) As StringBuilder
        'On transforme la chaine en tableau de byte
        Dim byteArray(value.Length - 1) As Byte
        Dim i As Integer = 0
        For Each item As Char In value.ToCharArray()
            byteArray(i) = CByte(AscW(item))
            i += 1
        Next

        'On prepare pour la compression
        Dim ms As New System.IO.MemoryStream()
        Dim sw As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)

        'On compresse
        sw.Write(byteArray, 0, byteArray.Length)
        sw.Close()

        'On convertit le tableau de bytes en string
        byteArray = ms.ToArray()
        Dim sB As New System.Text.StringBuilder(byteArray.Length)
        For Each item As Byte In byteArray
            sB.Append(ChrW(item))
        Next
        ms.Close()
        sw.Dispose()
        ms.Dispose()
        Return sB
    End Function

    Public Shared Function UnZip(value As String) As StringBuilder
        'On transforme la chaine en tableau de bytes
        Dim byteArray(value.Length - 1) As Byte
        Dim i As Integer = 0
        For Each item As Char In value.ToCharArray()
            byteArray(i) = CByte(AscW(item))
            i += 1
        Next

        'On prepare la decompression
        Dim ms As New System.IO.MemoryStream(byteArray)
        Dim sr As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
        byteArray = New Byte(byteArray.Length - 1) {}

        'On decompresse
        Dim rByte As Integer = sr.Read(byteArray, 0, byteArray.Length)

        'On convertit le tableau de bytes en string
        Dim sB As New System.Text.StringBuilder(rByte)
        For i = 0 To rByte - 1
            sB.Append(ChrW(byteArray(i)))
        Next
        sr.Close()
        ms.Close()
        sr.Dispose()
        ms.Dispose()
        Return sB
    End Function

End Class

Leave a Reply

Your email address will not be published. Required fields are marked *