Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Posts Tagged ‘compress’

Compressing and Decompressing files in C#.Net

Posted by Paul on November 16, 2010

In this tutorial I am trying to show the usage of .Net library to compress and decompress files.

GZipStream

We are using the class from namespace System.IO.Compression.

Basically the example, loads a text file compresses it into a file.

Compressing

private void Compress(string originalFile, string destinationFile)

{

    FileStream inStream = new FileInfo(originalFile).OpenRead();

    FileStream fileStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

 

    byte[] buffer = new byte[4096];

    int numRead;

    while ((numRead = inStream.Read(buffer, 0, buffer.Length)) != 0)

    {

        gzipStream.Write(buffer, 0, numRead);

    }

 

    gzipStream.Dispose();

    fileStream.Dispose();

    inStream.Dispose();

}

Decompressing

private void Decompress(string compressedFile, string destinationFile)

{

    FileStream compressedStream = new FileInfo(compressedFile).OpenRead();

    FileStream destinationStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);

    byte[] buffer = new byte[4096];

 

    int numRead;

 

    while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)

    { 

        destinationStream.Write(buffer, 0, numRead); 

    }

 

    gzipStream.Dispose();

    destinationStream.Dispose();

    compressedStream.Dispose();

}

Advertisements

Posted in C# | Tagged: , , | Leave a Comment »