How to compress and decompress data in c#

This post will show you how to compress and decompress data in c# using the GzipStream class. Below is the code for the same.
GzipStream class is built-in.NetFramework, so no need to download any software for it.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO.Compression;
namespace CompressDecompress
{
    class Program
    {
    const string CompressFilePath = @"C:\temp\data.zip";
    const string Filename = @"C:\temp\data.txt";
    private const string DeCompressFilePath = @"C:\temp\data1.txt";
    static void Main(string[] args)
        {
            Compress(Filename);
            Decompress(CompressFilePath);
        }
    private static void Decompress(string compressFilePath)
        {
    using (FileStream inputStream = new FileStream(compressFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
    using (FileStream outputStream = new FileStream(DeCompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
    using (GZipStream gZipStream = new GZipStream(inputStream, CompressionMode.Decompress))
                    {
                        gZipStream.CopyTo(outputStream);
                    }
                }
            }
        }
    private static void Compress(string filename)
        {
    using (FileStream inputStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                Console.WriteLine("Size Before Compression:{0} KB", inputStream.Length / 1024);
    using (FileStream outputStream = new FileStream(CompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
    using (GZipStream gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
                    {
                        inputStream.CopyTo(gZipStream);
                        Console.WriteLine("Size after Compression:{0} KB", outputStream.Length / 1024);
                    }
                }
            }
        }
    }
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post