GZipStream Class to Compress and Decompress Stream Data

  • 6

GZipStream Class to Compress and Decompress Stream Data

Provides methods and properties used to compress and decompress streams.

Namespace: System.IO.Compression
Assembly: System (in system.dll)

 

This class represents the gzip data format, which uses an industry standard algorithm for lossless file compression and decompression. The format includes a cyclic redundancy check value for detecting data corruption. The gzip data format uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats. The format can be readily implemented in a manner not covered by patents. The format for gzip is available from the RFC 1952, “GZIP .” This class cannot be used to compress files larger than 4 GB.

 

Notes to Inheritors When you inherit from GZipStream, you must override the following members: CanSeek, CanWrite, and CanRead.

 

 Example

The following code example shows how to use the GZipStream class to compress and decompress a file.

using System;
using System.IO;
using System.IO.Compression;

public class GZipTest
{
    public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
    {
    // Use this method is used to read all bytes from a stream.
    int offset = 0;
    int totalCount = 0;
        while (true)
        {
        int bytesRead = stream.Read(buffer, offset, 100);
            if ( bytesRead == 0)
            {
            break;
            }
    offset += bytesRead;
    totalCount += bytesRead;
        }
    return totalCount;
    }

    public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
    {
        // Use this method to compare data from two different buffers.
        if (len1 != len2)
        {
        Console.WriteLine(“Number of bytes in two buffer are different {0}:{1}”, len1, len2);
        return false;
        }

        for ( int i= 0; i< len1; i++)
        {
            if ( buf1[i] != buf2[i])
            {
            Console.WriteLine(“byte {0} is different {1}|{2}”, i, buf1[i], buf2[i]);
            return false;
            }
        }
    Console.WriteLine(“All bytes compare.”);
    return true;
    }

    public static void GZipCompressDecompress(string filename)
    {
    Console.WriteLine(“Test compression and decompression on file {0}”, filename);
    FileStream infile;
        try
        {
        // Open the file as a FileStream object.
        infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
            if ( count != buffer.Length)
            {
            infile.Close();
            Console.WriteLine(“Test Failed: Unable to read data from file”);
            return;
            }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // Use the newly created memory stream for the compressed data.
        GZipStream compressedzipStream = new GZipStream(ms , CompressionMode.Compress, true);
        Console.WriteLine(“Compression”);
        compressedzipStream.Write(buffer, 0, buffer.Length);
        // Close the stream.
        compressedzipStream.Close();
        Console.WriteLine(“Original size: {0}, Compressed size: {1}”, buffer.Length, ms.Length);

        // Reset the memory stream position to begin decompression.
        ms.Position = 0;
        GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
        Console.WriteLine(“Decompression”);
        byte[] decompressedBuffer = new byte[buffer.Length + 100];
        // Use the ReadAllBytesFromStream to read the stream.
        int totalCount = GZipTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
        Console.WriteLine(“Decompressed {0} bytes”, totalCount);

        if( !GZipTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount) )
        {
        Console.WriteLine(“Error. The two buffers did not compare.”);
        }
    zipStream.Close();
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine(“Error: The file being read contains invalid data.”);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine(“Error:The file specified was not found.”);
        }
        catch (ArgumentException)
        {
            Console.WriteLine(“Error: path is a zero-length string, contains only white space, or contains one or more invalid characters”);
        }
        catch (PathTooLongException)
        {
            Console.WriteLine(“Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.”);
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine(“Error: The specified path is invalid, such as being on an unmapped drive.”);
        }
        catch (IOException)
        {
            Console.WriteLine(“Error: An I/O error occurred while opening the file.”);
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine(“Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.”);
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine(“Error: You must provide parameters for MyGZIP.”);
        }
    }
    public static void Main(string[] args)
    {
        string usageText = “Usage: MYGZIP <inputfilename>”;
        //If no file name is specified, write usage text.
        if (args.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            if (File.Exists(args[0]))
                GZipCompressDecompress(args[0]);
        }
    }
}
   

Demo Application:

 

Default.aspx :

 

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head runat=”server”>

<title>Compression Demo</title>

</head>

<body style=”margin-top:10; margin-left:0″>

<form id=”form1″ runat=”server”>

<div>

<asp:Panel ID=”Panel1″ runat=”server” Height=”500px” Width=”100%” HorizontalAlign=”Center”>

<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True” Font-Size=”Large” Font-Underline=”True”

Text=”File Upload & Compression Tutorial”></asp:Label><br />

<br />

<table style=”width: 100%”>

<tr>

<td align=”right”>

<asp:Label ID=”Label2″ runat=”server” Text=”File to upload and compress: “ Width=”100%”></asp:Label></td>

<td style=”width: 100px” align=”left”>

<input id=”fileUpload” type=”file” runat=”server” />

</td>

</tr>

<tr>

<td>

</td>

<td style=”width: 50%” align=”left”>

<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />

<asp:Button ID=”btnCompress” runat=”server” Text=”Upload & Compress” /></td>

</tr>

<tr>

<td>

</td>

<td align=”left”>

<asp:Label ID=”lblResult” runat=”server” Font-Bold=”True” ForeColor=”RoyalBlue” Width=”100%”></asp:Label></td>

</tr>

</table>

</asp:Panel>

</div>

</form>

</body>

</html>

Default.aspx.cs :

Imports System.IO

Imports System.IO.Compression

 

Partial Class _Default

Inherits System.Web.UI.Page

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click

If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = “No File Selected to Upload.”

Exit Sub

End If

‘Retrieve file information and upload to server.

Dim strName As String

strName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)

Try

fileUpload.PostedFile.SaveAs(Server.MapPath(strName))

Me.lblResult.Text = “””” + strName + “”” was uploaded successfully.”

Catch ex As Exception

Me.lblResult.Text = “An Error Occured While Uploading File.”

End Try

End Sub

Protected Sub btnUploadCompressed_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompress.Click

If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = “No File Selected to Upload.”

Exit Sub

End If

Try

‘A String object reads the file name (locally)

Dim strName As String = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)

‘Create a stream object to read the file.

Dim myStream As Stream = fileUpload.PostedFile.InputStream

‘Allocate space in buffer for use according to length of file.

Dim myBuffer(myStream.Length) As Byte

‘Read the file using the Stream object and fill the buffer.

myStream.Read(myBuffer, 0, myBuffer.Length)

myStream.Close()

‘Change the extension of the file creating a FileStream object.

Dim myCompressedFile As FileStream = File.Create(Server.MapPath(Path.ChangeExtension(strName, “rar”)))

‘GZip object that compress the file

Dim myStreamZip As New System.IO.Compression.GZipStream(myCompressedFile, CompressionMode.Compress)

‘Write Back

myStreamZip.Write(myBuffer, 0, myBuffer.Length)

myStreamZip.Close()

Me.lblResult.Text = “””” + strName + “”” was uploaded successfully and compressed.”

Catch ex As Exception

Me.lblResult.Text = “An Error Occured While Uploading File.”

End Try

End Sub

End Class


Bookmark and Share


6 Comments

ruou vang

November 5, 2011 at 12:41 pm

ruou vang…

[…]GZipStream Class to Compress and Decompress Stream Data « Zonix Software Solutions[…]…

Cary

March 20, 2013 at 5:44 am

If you are looking to take turmeric as part of a dietary supplement,
check out Xend Life Total Balance, a natural supplement that includes many natural herbs, including turmeric.
Another way for the softness your lip is to gently rub Aloe
Vera gel mixed with oatmeal and goat milk and rinse off.
Here spices are believed to have high medicinal
or curative measures which make these spices special.

hacking software

April 13, 2013 at 3:29 am

Hello There. I found your blog using msn. This is a really well written article.
I’ll make sure to bookmark it and return to read more of your useful info. Thanks for the post. I will definitely comeback.

and Cheat Codes

April 24, 2013 at 5:29 pm

Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.

I think that you can do with some pics to drive the message
home a little bit, but other than that, this is wonderful blog.
An excellent read. I’ll definitely be back.

walkfit platinum reviews

June 26, 2013 at 7:23 am

Hello there. I uncovered a person’s weblog use of windows live messenger. This is the wonderfully published post. I’m going to you should definitely book mark the idea plus come back to learn more within your helpful information. Thanks for your article. I am going to surely comeback.

Albertha

July 28, 2014 at 3:35 pm

Youll be able to get updates from the vendor that sold you the anti-virus software,
such as Norton. Whatever may be the reason for
which you might be opting for this software, it is highly recommended to make essential research about the product before
opting for it. Thus, if the online marketer is using 20 keywords for his
campaign, then the software will create 20 pages.

Leave a Reply