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

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


    End Sub


    Private Function GetRandomString(ByVal size As Integer) As String

        Dim sb As New StringBuilder()
        Dim Rand As New Random

        For i As Integer = 0 To size - 1
            Dim ch As Char = Convert.ToChar(Rand.Next(33, 126))
            sb.Append(ch)
        Next
        Return sb.ToString()
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Najpierw tworzymy plik bez kompresji.
        Dim fsNoCompress As New FileStream("c:\nocompress", FileMode.Create)
        Dim rNoCompress As New BinaryWriter(fsNoCompress)

        ' Teraz tworzymy plik skompresowany.
        Dim fsCompress As New FileStream("c:\compress", FileMode.Create)

        ' You need to create a GZipStream in Compress mode. It wraps the FileStream.
        ' Tworzymy obiekt, skompresowany strumień GZipStream 
        ' w trybie "CompressionMode.Compress", który "zipuje" strumień FileStream
        Dim CompressStream As New GZipStream(fsCompress, CompressionMode.Compress)

        ' The BinaryWriter writes to the GZipStream, not the FileStream.
        ' Obiekt BinaryWriter przesyła dane do GZipStream, a nie do strumienia FileStream.
        Dim rCompress As New BinaryWriter(CompressStream)

        ' Write 1,000 random strings (each 30 characters long) to both files.
        ' do obu plików zapisujemy 1000 losowych łańcuchów po 30 znaków każdy.
        For i As Integer = 1 To 10000
            Dim RandomString As String = GetRandomString(30)
            rNoCompress.Write(RandomString)
            rCompress.Write(RandomString)
        Next

        ' Zamykamy oba pliki.
        rNoCompress.Close()
        fsNoCompress.Close()

        rCompress.Close()
        fsCompress.Close()

        ' Porównujemy wielkość plików.
        MessageBox.Show("Dane z pliku o wiekości " & _
          My.Computer.FileSystem.GetFileInfo("c:\nocompress").Length & _
          " bajtów skompresowano do " & _
          My.Computer.FileSystem.GetFileInfo("c:\compress").Length & _
          " bajtów.")

        ' Odczyt danych z dekompresją.
        Dim fsRead As New FileStream("c:\compress", FileMode.Open)
        Dim DecompressStream As New GZipStream(fsRead, CompressionMode.Decompress)
        Dim r As New BinaryReader(DecompressStream)
        ' To odczyt danych.
        ' W okienku pokazujemy pierwszy odczytany łańcuch znaków.
        MessageBox.Show("Skompresowane dane wygladają tak: " & r.ReadString())
        r.Close()
        fsRead.Close()

    End Sub
End Class
