///
/// 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