How to Compress and Decompress File in Asp.net


Description:-

Most people have downloaded large files, such as music or video, from the Internet. Because of the large size of these files, downloading them can take hours. To solve this problem, and make better use of disk space, large files are compressed, using various software. Once downloaded, they can then be decompressed, and viewed, using a decompression program. In this Article we will Show to Compress and Decompress File Using Zip Stream in Asp.net.

Compress File Code

Create Method in your Webpage Code behind and Call in your Page_load event.

public void Compress()
{
  string fileToBeCompressed = @"D:\Document.doc";
  string zipFilename = @"D:\Document.zip";
  using (FileStream target = new FileStream(zipFilename, FileMode.Create, FileAccess.Write))
  using (GZipStream alg = new GZipStream(target, CompressionMode.Compress))
  {
    byte[] data = File.ReadAllBytes(fileToBeCompressed);
    alg.Write(data, 0, data.Length);
    alg.Flush();
  }
}

Decompress File Code

Create Method In your Webpage and Call in your Page_load event. it will shows on how to do a decompress file using C# code that is already compressed. 

public void Decompress()
{
  string compressedFile = @"D: \Uploads\Document.zip";
  string originalFileName = @"D: \Uploads\Document1.doc";
  using (FileStream zipFile = new FileStream(compressedFile, FileMode.Open, FileAccess.Read))
  using (FileStream originalFile = new FileStream(originalFileName, FileMode.Create, FileAccess.Write))
  using (GZipStream alg = new GZipStream(zipFile, CompressionMode.Decompress))
  {
    while (true)
    {
      byte[] buffer = new byte[100];
      int bytesRead = alg.Read(buffer, 0, buffer.Length);
      originalFile.Write(buffer, 0, bytesRead);
      if (bytesRead != buffer.Length)
      break;
    }
  }
}

Related Posts

Previous
Next Post »

Thanks for comments.....