File Compression Using the .NET GZipStream Class
Posted by Rhonda Tipton on June 7, 2008
The GZipStream class is a part of the System.IO.Compression namespace. This class is used for the compression of data. Before the .NET 2.0 Framework, the only choice we had for compression were third party tools.
–
Common Methods (Full List)
- BeginRead - Begins an asynchronous read operation.
- BeginWrite - Begins an asynchronous write operation.
- Close - Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
- EndRead - Waits for the pending asynchronous read to complete.
- EndWrite - Handles the end of an asynchronous write operation.
- Read - Reads a number of decompressed bytes into the specified byte array.
- Write - Writes compressed bytes to the underlying stream from the specified byte array.
–
Below is a simple C# console application that takes an input file, compresses it and creates a compressed zip file.
C# Listing
using System; using System.IO; using System.IO.Compression; public class GZipTest { private static void usage() { Console.WriteLine(“My test GZip program”); Console.WriteLine(“gziptest [filename to be compressed]“); } static void Main(string[] args) { if (args.Length < 1) { usage(); return; } else { string inputFile = args[0]; string outputFile = inputFile + “.gz”; try { // Get bytes from input stream FileStream inFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, inputFile), FileMode.Open); byte[] buffer = new byte[inFileStream.Length]; inFileStream.Read(buffer, 0, buffer.Length); inFileStream.Close(); // Create GZip file stream and compress input bytes FileStream outFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, outputFile), FileMode.Create); GZipStream compressedStream = new GZipStream(outFileStream, CompressionMode.Compress); compressedStream.Write(buffer, 0, buffer.Length); compressedStream.Close(); outFileStream.Close(); Console.WriteLine(“The file has been compressed. UR Da Bomb!!!”); } catch(FileNotFoundException) { Console.WriteLine(“Error: Specified file cannot be found.”); } } } }
–
The command-line illustration below shows the application at work.
- If no argument is provided, the usage syntax is echoed to the screen
- If the argument provided cannot be located, error is echoed to the screen
- If correct argument is provided, the file is compressed and a new file is created
The result (compressed) file created.
View the compressed file in a Zip application.
–
The GZipStream class is not as feature-rich as the third-party tools, but it is a convenient way to compress data.
–
Related Content
–
Happy programming…
Posted in C# | 2 Comments »



































