Wednesday 30 June, 2010

Compress/Decompress Files using System.IO.Compression.GZipStream Class [2.0]

I was in need to compress and decompress files in one of the projects im currently working on. At the start i only knew about GZipStream existance in 2.0 but never used it before. So today i used it and i was able to compress and decompress the files back when i need to. Below are two functions

///
/// To Compress A File
///

/// The Complete file path to the file you want to compress
protected void Compress(string filePath)
{
FileStream sourceFile = File.OpenRead(filePath);
FileStream destinationFile = File.Create(Server.MapPath("~") + "/tv.gzip");
byte[] buffer = new byte[sourceFile.Length];
GZipStream zip = null;
try
{
sourceFile.Read(buffer, 0, buffer.Length);
zip = new GZipStream(destinationFile, CompressionMode.Compress);
zip.Write(buffer, 0, buffer.Length);
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
zip.Close();
sourceFile.Close();
destinationFile.Close();
}
}

///
/// To Decompress an already compressed file
///

/// The complete file path of the already compressed file
protected void Decompress(string filePath)
{
FileStream sourceFile = File.OpenRead(filePath);
FileStream destinationFile = File.Create(Server.MapPath("~") + "/tv1.xml");
GZipStream unzip = null;
byte[] buffer = new byte[sourceFile.Length];
try
{
unzip = new GZipStream(sourceFile, CompressionMode.Decompress, false);
int numberOfBytes = unzip.Read(buffer, 0, buffer.Length);

destinationFile.Write(buffer, 0, numberOfBytes);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
sourceFile.Close();
destinationFile.Close();
unzip.Close();
}
}

N.B: Do not forget to import two namespaces

1.
System.IO
2.
System.IO.Compression

Best Regards,

No comments:

Post a Comment