A Dutch software developer living in Chile
# Monday, July 27, 2009
A very simple GZip command line tool

During some testing, I needed a tool that could simply compress a file to GZip format and back again. I decided that other people might have a similar need, so here’s the code to make it work.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Compression;
using System.IO;

namespace GZip
{
  class Program
  {
    static void Main(string[] args)
    {
      CompressionMode mode = CompressionMode.Compress;

      if (args.Length != 3)
      {
        ShowUsage();
        return;
      }

      string command = args[0].ToLower();
      switch (command)
      {
        case "compress":
          mode = CompressionMode.Compress;
          break;
        case "decompress":
          mode = CompressionMode.Decompress;
          break;
        default:
          ShowUsage();
          return;
      }

      Stream sourceStream = File.OpenRead(args[1]);
      Stream targetStream = File.OpenWrite(args[2]);

      switch (mode)
      {
        case CompressionMode.Compress:
          using (GZipStream gZip = new GZipStream(targetStream, CompressionMode.Compress))
          {
            Pump(sourceStream, gZip);
          }

          break;
        case CompressionMode.Decompress:
          using (GZipStream gZip = new GZipStream(sourceStream, CompressionMode.Decompress))
          {
            Pump(gZip, targetStream);
          }
          break;
      }
      sourceStream.Close();
      targetStream.Close();

    }

    private static void Pump(Stream source, Stream target)
    {
      byte[] buffer = new byte[65536];
      int count;
      while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
      {
        target.Write(buffer, 0, count);
      }

    }

    private static void ShowUsage()
    {
      Console.WriteLine("Usage: GZip compress | decompress   sourceFileName targetFileName");
    }
  }
}


Monday, July 27, 2009 3:02:34 PM (Pacific SA Standard Time, UTC-04:00)  #    Comments [0]  Programming

Comments are closed.