Wednesday, 13 June 2012

C# Tips : Compress and Decompress file or data using C# and VB.Net

.Net framework provide the System.IO.Compression.GZipStream or System.IO.Compression.DeflateStream to compress or decompress data.
Both GZipStream and DeflateStream classes allow you to use GZIP and Deflate compression algorithms to compress or decompress data.

Here are sample examples with GZipStream class.
The sample examples there are two methods one is CompressData and other is DCompressData.
In CompressData method we create a new file and uses the GZipStream class to write compressed file to it and close that file .
In DCompressData method we open that compressed file in read mode and decompressed the file and save.
In this sample you have to provide the file path which file you want to compress and also provide file path where the compressed file stored.
In this example we store both files in application root directory.

This examples are in both C# and VB.Net .

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {

        CompressData();
        DCompressData();
             
    }
    void CompressData()
    {
        // Create the compression stream.
        GZipStream objGZipOut = new GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress);
        
        int intBufferLength = 16 * 1024;
        byte[] objBuffer = new byte[intBufferLength];

        // Get File Stream Object
        System.IO.FileStream objFileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write file Content 
            objGZipOut.Write(objBuffer, 0, len);

        }
        objFileStream.Close();
        objGZipOut.Close();
       
    }
    void DCompressData()
    {
        // Open the same gzip file to decompress
        GZipStream objGZipIn = new GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress);

        // Get stream reader of the gzip file.
        StreamReader objReader = new StreamReader(objGZipIn);
       
        byte[] buffer = new byte[16 * 1024];
        int len = 0;
        FileStream objFS = new FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
        while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            objFS.Write(buffer, 0, len);
        }
        objFS.Close();
        objReader.Close();
        objGZipIn.Close();
       
    }


VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CompressData()
        DCompressData()
    End Sub
    Private Sub CompressData()
        ' Create the compression stream.
        Dim objGZipOut As New GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress)

        Dim intBufferLength As Integer = 16 * 1  '1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        ' Get File Stream Object
        Dim objFileStream As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim len As Integer = 0
        len = objFileStream.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Write file Content 
            objGZipOut.Write(objBuffer, 0, len)
            len = objFileStream.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStream.Close()
        objGZipOut.Close()

    End Sub
    Private Sub DCompressData()
        ' Open the same gzip file to decompress
        Dim objGZipIn As New GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress)

        ' Get stream reader of the gzip file.
        Dim objReader As New StreamReader(objGZipIn)

        Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
        Dim len As Integer = 0
        Dim objFS As New FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
        len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        While len <> 0
            objFS.Write(buffer, 0, len)
            len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        End While
        
        objFS.Close()
        objReader.Close()
        objGZipIn.Close()

    End Sub

You can also provide other data like simple string to compress data , for that you have to use stream writer and use it's WriteLine method.

In this example we provide "TextFile.txt" text file. Size of this text file is 3 kb.
After the compressing new file "compressed_data.gzip" generated and it's size is 1 kb.

Output :

Before compression 



After compression 



12 comments:

  1. Lot of questions have raised after the release of dot Net core and dot net framework. I have seen some reasonable answer for all those questions. Thanks for your answers and differences between .Net Core and .Net framework.
    Regards:
    DOT NET Training in Chennai | DOT NET Course in Chennai

    ReplyDelete
  2. I have gone through your blog, it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic. Kindly post more like this, Thank You. i reay enjoy to read this
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  3. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Big Data Hadoop Training in Chennai | Infycle Technologies for students, freshers, and tech professionals. Infycle also offers other professional courses such as DevOps, Artificial Intelligence, Cyber Security, Python, Oracle, Java, Power BI, Selenium Testing, Digital Marketing, Data Science, etc., which will be trained with 200% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7502633633 to get more info and a free demo.

    ReplyDelete
  4. Avid Sibelius Ultimate 2022.10 Crack That can plan the design of a few stories. The client can score three managed logos generally.Sibelius Ultimate Free Download

    ReplyDelete