Saturday, May 25, 2013

Compress and DeCompress pdf and other files using C#.Net

Step-1 
protected void compressFile()
{
  FileStream sourceFileStream = File.OpenRead(Server.MapPath("myDoc1.pdf"));
  FileStream destFileStream = File.Create(Server.MapPath("myDoc1.pdf.gz"));
  GZipStream compressingStream = new GZipStream(destFileStream, CompressionMode.Compress);
  byte[] bytes = new byte[2048];
  int bytesRead;

 while ((bytesRead = sourceFileStream.Read(bytes, 0, bytes.Length)) != 0)
 {
   compressingStream.Write(bytes, 0, bytesRead);
 }
  sourceFileStream.Close();
  compressingStream.Close();
  destFileStream.Close();
}



Step-2

protected void DeCompressFile()
{
  FileStream sourceFileStream = File.OpenRead(Server.MapPath("myDoc1.pdf.gz"));
  FileStream destFileStream = File.Create(Server.MapPath("myDoc1.pdf"));
  GZipStream decompressingStream = new GZipStream(sourceFileStream, CompressionMode.Decompress);
 int byteRead;
 while ((byteRead = decompressingStream.ReadByte()) != -1)
 {
  destFileStream.WriteByte((byte)byteRead);
 }
 decompressingStream.Close();
 sourceFileStream.Close();
 destFileStream.Close();
}

Step-3: Drag two buttons on your page and set their ID as btnCompress, btnDecompress and call compressFile() and DeCompressFile() functions respectively on their click events.

protected void btnCompress_Click(object sender, EventArgs e)
{
 compressFile();
}


protected void btnDecompress_Click(object sender, EventArgs e)
{
 DeCompressFile();
}


Thats it.

No comments:

Post a Comment

SharePoint Deployment Error : The specified path, file name, or both are too long.

Hi, Sometimes we get surprised with below error while deploying wsp file... Solution : To overcome with this issue, we just ne...