File compression using C#.Net

Follow 3 simple steps:

1. Add a new .cs file in your project and add the below namespaces.

using System.IO;
using System.IO.Compression;

2. Add the below code; use this function for compressing the file.

static void CompressFile(string inFileName, string outFileName)
{
     FileStream sourceFile = File.Open(inFileName, FileMode.Open);
     FileStream destFilename = File.Open(outFileName, FileMode.Create);

     GZipStream compStream = new GZipStream(destFilename, CompressionMode.Compress);
            
     Byte[] buffer = new Byte[1024*1024];
     int tempByte = sourceFile.Read(buffer,0,buffer.Length);
     while (tempByte > 0)
     {                
          compStream.Write(buffer, 0, buffer.Length);
          tempByte = sourceFile.Read(buffer, 0, buffer.Length);
     }
     compStream.Close();
     destFilename.Close();
     sourceFile.Close();
}


3. Add the below code; use this function for uncompressing the file.

static void UnCompressFile(string inFileName, string outFileName)
{
     FileStream sourceFile = File.Open(inFileName, FileMode.Open);
     FileStream destFilename = File.Open(outFileName, FileMode.Create);

     GZipStream compStream = new GZipStream(destFilename, CompressionMode.Decompress);
            
     int tempByte = compStream.ReadByte();
     while (tempByte != -1)
     {    destFilename.WriteByte((Byte)tempByte);
          tempByte = compStream.ReadByte();
     }
     compStream.Close();
     destFilename.Close();
     sourceFile.Close();
}