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
/// <summary>
/// To Compress A File
/// </summary>
/// <param name="filePath">The Complete file path to the file you want to compress</param>
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();
}
}
/// <summary>
/// To Decompress an already compressed file
/// </summary>
/// <param name="filePath">The complete file path of the already compressed file</param>
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
-
System.IO
-
System.IO.Compression
Best Regards,