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