Compress text file

If you want to compress file, you can leverage of the standard .NET classes. You can use either GZipStream or DeflateStream class. Both classes are located in the System:::IO:::Compression namespace, so you'll need to use import namespace directive to be able to use these classes. Constructors of these classes accept stream to use for writing (when compressing) or reading (when decompressing) as a first and mode (either Compress or Decompress) as a second parameter.

If you want to write the result to the file (which should have "gz" extension if you use GZipStream) you need to create instance of FileStream. Constructor of this class requires two parameters - first parameter is the file name and the second parameter is access mode. If you want to create a new file (or overwrite existing) you can use FileMode::Create.

The script that can be used for compressing text files looks like this (Program.php):
<?
import namespace System;
import namespace System:::IO;
import namespace System:::IO:::Compression;

// function compresses $in file to gz $out file
function compress($in, $out)
{
  // Read content of the file to $text variable
  $insr = new StreamReader($in);
  $text = $insr->ReadToEnd();
  $insr->Close();

  // Write text to GZ file 
  $outf = new FileStream($out, FileMode::Create);
  $outsw = new StreamWriter(new GZipStream($outf, CompressionMode::Compress));
  $outsw->Write($text);	
  $outsw->Close();
  $outf->Close();
}

// call the compress function
compress("Input.txt", "Input.gz");
?> 


When compiling the file, you have to specify that you want to enable PHP/CLR extensions that allow you to use standard .NET classes. This can be done by specifying /lang:clr command line parameter:
phpc /lang:clr program.php 

Last edited Oct 10, 2006 at 9:05 PM by tomasp, version 1

Comments

nagraj Oct 11, 2006 at 5:53 AM 
Is it possible to compress a folder and its subfolders.